Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot.errors import ParseError
  25from sqlglot.helper import (
  26    AutoName,
  27    camel_to_snake_case,
  28    ensure_collection,
  29    ensure_list,
  30    seq_get,
  31    split_num_words,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39E = t.TypeVar("E", bound="Expression")
  40
  41
  42class _Expression(type):
  43    def __new__(cls, clsname, bases, attrs):
  44        klass = super().__new__(cls, clsname, bases, attrs)
  45
  46        # When an Expression class is created, its key is automatically set to be
  47        # the lowercase version of the class' name.
  48        klass.key = clsname.lower()
  49
  50        # This is so that docstrings are not inherited in pdoc
  51        klass.__doc__ = klass.__doc__ or ""
  52
  53        return klass
  54
  55
  56class Expression(metaclass=_Expression):
  57    """
  58    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  59    context, such as its child expressions, their names (arg keys), and whether a given child expression
  60    is optional or not.
  61
  62    Attributes:
  63        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  64            and representing expressions as strings.
  65        arg_types: determines what arguments (child nodes) are supported by an expression. It
  66            maps arg keys to booleans that indicate whether the corresponding args are optional.
  67
  68    Example:
  69        >>> class Foo(Expression):
  70        ...     arg_types = {"this": True, "expression": False}
  71
  72        The above definition informs us that Foo is an Expression that requires an argument called
  73        "this" and may also optionally receive an argument called "expression".
  74
  75    Args:
  76        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  77        parent: a reference to the parent expression (or None, in case of root expressions).
  78        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  79            uses to refer to it.
  80        comments: a list of comments that are associated with a given expression. This is used in
  81            order to preserve comments when transpiling SQL code.
  82        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  83            optimizer, in order to enable some transformations that require type information.
  84    """
  85
  86    key = "expression"
  87    arg_types = {"this": True}
  88    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  89
  90    def __init__(self, **args: t.Any):
  91        self.args: t.Dict[str, t.Any] = args
  92        self.parent: t.Optional[Expression] = None
  93        self.arg_key: t.Optional[str] = None
  94        self.comments: t.Optional[t.List[str]] = None
  95        self._type: t.Optional[DataType] = None
  96        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  97        self._hash: t.Optional[int] = None
  98
  99        for arg_key, value in self.args.items():
 100            self._set_parent(arg_key, value)
 101
 102    def __eq__(self, other) -> bool:
 103        return type(self) is type(other) and hash(self) == hash(other)
 104
 105    @property
 106    def hashable_args(self) -> t.Any:
 107        args = (self.args.get(k) for k in self.arg_types)
 108
 109        return tuple(
 110            (tuple(_norm_arg(a) for a in arg) if arg else None)
 111            if type(arg) is list
 112            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 113            for arg in args
 114        )
 115
 116    def __hash__(self) -> int:
 117        if self._hash is not None:
 118            return self._hash
 119
 120        return hash((self.__class__, self.hashable_args))
 121
 122    @property
 123    def this(self):
 124        """
 125        Retrieves the argument with key "this".
 126        """
 127        return self.args.get("this")
 128
 129    @property
 130    def expression(self):
 131        """
 132        Retrieves the argument with key "expression".
 133        """
 134        return self.args.get("expression")
 135
 136    @property
 137    def expressions(self):
 138        """
 139        Retrieves the argument with key "expressions".
 140        """
 141        return self.args.get("expressions") or []
 142
 143    def text(self, key) -> str:
 144        """
 145        Returns a textual representation of the argument corresponding to "key". This can only be used
 146        for args that are strings or leaf Expression instances, such as identifiers and literals.
 147        """
 148        field = self.args.get(key)
 149        if isinstance(field, str):
 150            return field
 151        if isinstance(field, (Identifier, Literal, Var)):
 152            return field.this
 153        if isinstance(field, (Star, Null)):
 154            return field.name
 155        return ""
 156
 157    @property
 158    def is_string(self) -> bool:
 159        """
 160        Checks whether a Literal expression is a string.
 161        """
 162        return isinstance(self, Literal) and self.args["is_string"]
 163
 164    @property
 165    def is_number(self) -> bool:
 166        """
 167        Checks whether a Literal expression is a number.
 168        """
 169        return isinstance(self, Literal) and not self.args["is_string"]
 170
 171    @property
 172    def is_int(self) -> bool:
 173        """
 174        Checks whether a Literal expression is an integer.
 175        """
 176        if self.is_number:
 177            try:
 178                int(self.name)
 179                return True
 180            except ValueError:
 181                pass
 182        return False
 183
 184    @property
 185    def is_star(self) -> bool:
 186        """Checks whether an expression is a star."""
 187        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 188
 189    @property
 190    def alias(self) -> str:
 191        """
 192        Returns the alias of the expression, or an empty string if it's not aliased.
 193        """
 194        if isinstance(self.args.get("alias"), TableAlias):
 195            return self.args["alias"].name
 196        return self.text("alias")
 197
 198    @property
 199    def name(self) -> str:
 200        return self.text("this")
 201
 202    @property
 203    def alias_or_name(self):
 204        return self.alias or self.name
 205
 206    @property
 207    def output_name(self):
 208        """
 209        Name of the output column if this expression is a selection.
 210
 211        If the Expression has no output name, an empty string is returned.
 212
 213        Example:
 214            >>> from sqlglot import parse_one
 215            >>> parse_one("SELECT a").expressions[0].output_name
 216            'a'
 217            >>> parse_one("SELECT b AS c").expressions[0].output_name
 218            'c'
 219            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 220            ''
 221        """
 222        return ""
 223
 224    @property
 225    def type(self) -> t.Optional[DataType]:
 226        return self._type
 227
 228    @type.setter
 229    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 230        if dtype and not isinstance(dtype, DataType):
 231            dtype = DataType.build(dtype)
 232        self._type = dtype  # type: ignore
 233
 234    @property
 235    def meta(self) -> t.Dict[str, t.Any]:
 236        if self._meta is None:
 237            self._meta = {}
 238        return self._meta
 239
 240    def __deepcopy__(self, memo):
 241        copy = self.__class__(**deepcopy(self.args))
 242        if self.comments is not None:
 243            copy.comments = deepcopy(self.comments)
 244
 245        if self._type is not None:
 246            copy._type = self._type.copy()
 247
 248        if self._meta is not None:
 249            copy._meta = deepcopy(self._meta)
 250
 251        return copy
 252
 253    def copy(self):
 254        """
 255        Returns a deep copy of the expression.
 256        """
 257        new = deepcopy(self)
 258        new.parent = self.parent
 259        return new
 260
 261    def append(self, arg_key, value):
 262        """
 263        Appends value to arg_key if it's a list or sets it as a new list.
 264
 265        Args:
 266            arg_key (str): name of the list expression arg
 267            value (Any): value to append to the list
 268        """
 269        if not isinstance(self.args.get(arg_key), list):
 270            self.args[arg_key] = []
 271        self.args[arg_key].append(value)
 272        self._set_parent(arg_key, value)
 273
 274    def set(self, arg_key, value):
 275        """
 276        Sets `arg_key` to `value`.
 277
 278        Args:
 279            arg_key (str): name of the expression arg.
 280            value: value to set the arg to.
 281        """
 282        self.args[arg_key] = value
 283        self._set_parent(arg_key, value)
 284
 285    def _set_parent(self, arg_key, value):
 286        if hasattr(value, "parent"):
 287            value.parent = self
 288            value.arg_key = arg_key
 289        elif type(value) is list:
 290            for v in value:
 291                if hasattr(v, "parent"):
 292                    v.parent = self
 293                    v.arg_key = arg_key
 294
 295    @property
 296    def depth(self):
 297        """
 298        Returns the depth of this tree.
 299        """
 300        if self.parent:
 301            return self.parent.depth + 1
 302        return 0
 303
 304    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 305        """Yields the key and expression for all arguments, exploding list args."""
 306        for k, vs in self.args.items():
 307            if type(vs) is list:
 308                for v in vs:
 309                    if hasattr(v, "parent"):
 310                        yield k, v
 311            else:
 312                if hasattr(vs, "parent"):
 313                    yield k, vs
 314
 315    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
 316        """
 317        Returns the first node in this tree which matches at least one of
 318        the specified types.
 319
 320        Args:
 321            expression_types: the expression type(s) to match.
 322
 323        Returns:
 324            The node which matches the criteria or None if no such node was found.
 325        """
 326        return next(self.find_all(*expression_types, bfs=bfs), None)
 327
 328    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
 329        """
 330        Returns a generator object which visits all nodes in this tree and only
 331        yields those that match at least one of the specified expression types.
 332
 333        Args:
 334            expression_types: the expression type(s) to match.
 335
 336        Returns:
 337            The generator object.
 338        """
 339        for expression, *_ in self.walk(bfs=bfs):
 340            if isinstance(expression, expression_types):
 341                yield expression
 342
 343    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
 344        """
 345        Returns a nearest parent matching expression_types.
 346
 347        Args:
 348            expression_types: the expression type(s) to match.
 349
 350        Returns:
 351            The parent node.
 352        """
 353        ancestor = self.parent
 354        while ancestor and not isinstance(ancestor, expression_types):
 355            ancestor = ancestor.parent
 356        return t.cast(E, ancestor)
 357
 358    @property
 359    def parent_select(self):
 360        """
 361        Returns the parent select statement.
 362        """
 363        return self.find_ancestor(Select)
 364
 365    @property
 366    def same_parent(self):
 367        """Returns if the parent is the same class as itself."""
 368        return type(self.parent) is self.__class__
 369
 370    def root(self) -> Expression:
 371        """
 372        Returns the root expression of this tree.
 373        """
 374        expression = self
 375        while expression.parent:
 376            expression = expression.parent
 377        return expression
 378
 379    def walk(self, bfs=True, prune=None):
 380        """
 381        Returns a generator object which visits all nodes in this tree.
 382
 383        Args:
 384            bfs (bool): if set to True the BFS traversal order will be applied,
 385                otherwise the DFS traversal will be used instead.
 386            prune ((node, parent, arg_key) -> bool): callable that returns True if
 387                the generator should stop traversing this branch of the tree.
 388
 389        Returns:
 390            the generator object.
 391        """
 392        if bfs:
 393            yield from self.bfs(prune=prune)
 394        else:
 395            yield from self.dfs(prune=prune)
 396
 397    def dfs(self, parent=None, key=None, prune=None):
 398        """
 399        Returns a generator object which visits all nodes in this tree in
 400        the DFS (Depth-first) order.
 401
 402        Returns:
 403            The generator object.
 404        """
 405        parent = parent or self.parent
 406        yield self, parent, key
 407        if prune and prune(self, parent, key):
 408            return
 409
 410        for k, v in self.iter_expressions():
 411            yield from v.dfs(self, k, prune)
 412
 413    def bfs(self, prune=None):
 414        """
 415        Returns a generator object which visits all nodes in this tree in
 416        the BFS (Breadth-first) order.
 417
 418        Returns:
 419            The generator object.
 420        """
 421        queue = deque([(self, self.parent, None)])
 422
 423        while queue:
 424            item, parent, key = queue.popleft()
 425
 426            yield item, parent, key
 427            if prune and prune(item, parent, key):
 428                continue
 429
 430            for k, v in item.iter_expressions():
 431                queue.append((v, item, k))
 432
 433    def unnest(self):
 434        """
 435        Returns the first non parenthesis child or self.
 436        """
 437        expression = self
 438        while type(expression) is Paren:
 439            expression = expression.this
 440        return expression
 441
 442    def unalias(self):
 443        """
 444        Returns the inner expression if this is an Alias.
 445        """
 446        if isinstance(self, Alias):
 447            return self.this
 448        return self
 449
 450    def unnest_operands(self):
 451        """
 452        Returns unnested operands as a tuple.
 453        """
 454        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 455
 456    def flatten(self, unnest=True):
 457        """
 458        Returns a generator which yields child nodes who's parents are the same class.
 459
 460        A AND B AND C -> [A, B, C]
 461        """
 462        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 463            if not type(node) is self.__class__:
 464                yield node.unnest() if unnest else node
 465
 466    def __str__(self):
 467        return self.sql()
 468
 469    def __repr__(self):
 470        return self._to_s()
 471
 472    def sql(self, dialect: DialectType = None, **opts) -> str:
 473        """
 474        Returns SQL string representation of this tree.
 475
 476        Args:
 477            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 478            opts: other `sqlglot.generator.Generator` options.
 479
 480        Returns:
 481            The SQL string.
 482        """
 483        from sqlglot.dialects import Dialect
 484
 485        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 486
 487    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 488        indent = "" if not level else "\n"
 489        indent += "".join(["  "] * level)
 490        left = f"({self.key.upper()} "
 491
 492        args: t.Dict[str, t.Any] = {
 493            k: ", ".join(
 494                v._to_s(hide_missing=hide_missing, level=level + 1)
 495                if hasattr(v, "_to_s")
 496                else str(v)
 497                for v in ensure_list(vs)
 498                if v is not None
 499            )
 500            for k, vs in self.args.items()
 501        }
 502        args["comments"] = self.comments
 503        args["type"] = self.type
 504        args = {k: v for k, v in args.items() if v or not hide_missing}
 505
 506        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 507        right += ")"
 508
 509        return indent + left + right
 510
 511    def transform(self, fun, *args, copy=True, **kwargs):
 512        """
 513        Recursively visits all tree nodes (excluding already transformed ones)
 514        and applies the given transformation function to each node.
 515
 516        Args:
 517            fun (function): a function which takes a node as an argument and returns a
 518                new transformed node or the same node without modifications. If the function
 519                returns None, then the corresponding node will be removed from the syntax tree.
 520            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 521                modified in place.
 522
 523        Returns:
 524            The transformed tree.
 525        """
 526        node = self.copy() if copy else self
 527        new_node = fun(node, *args, **kwargs)
 528
 529        if new_node is None or not isinstance(new_node, Expression):
 530            return new_node
 531        if new_node is not node:
 532            new_node.parent = node.parent
 533            return new_node
 534
 535        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 536        return new_node
 537
 538    def replace(self, expression):
 539        """
 540        Swap out this expression with a new expression.
 541
 542        For example::
 543
 544            >>> tree = Select().select("x").from_("tbl")
 545            >>> tree.find(Column).replace(Column(this="y"))
 546            (COLUMN this: y)
 547            >>> tree.sql()
 548            'SELECT y FROM tbl'
 549
 550        Args:
 551            expression (Expression|None): new node
 552
 553        Returns:
 554            The new expression or expressions.
 555        """
 556        if not self.parent:
 557            return expression
 558
 559        parent = self.parent
 560        self.parent = None
 561
 562        replace_children(parent, lambda child: expression if child is self else child)
 563        return expression
 564
 565    def pop(self):
 566        """
 567        Remove this expression from its AST.
 568
 569        Returns:
 570            The popped expression.
 571        """
 572        self.replace(None)
 573        return self
 574
 575    def assert_is(self, type_):
 576        """
 577        Assert that this `Expression` is an instance of `type_`.
 578
 579        If it is NOT an instance of `type_`, this raises an assertion error.
 580        Otherwise, this returns this expression.
 581
 582        Examples:
 583            This is useful for type security in chained expressions:
 584
 585            >>> import sqlglot
 586            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 587            'SELECT x, z FROM y'
 588        """
 589        assert isinstance(self, type_)
 590        return self
 591
 592    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 593        """
 594        Checks if this expression is valid (e.g. all mandatory args are set).
 595
 596        Args:
 597            args: a sequence of values that were used to instantiate a Func expression. This is used
 598                to check that the provided arguments don't exceed the function argument limit.
 599
 600        Returns:
 601            A list of error messages for all possible errors that were found.
 602        """
 603        errors: t.List[str] = []
 604
 605        for k in self.args:
 606            if k not in self.arg_types:
 607                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 608        for k, mandatory in self.arg_types.items():
 609            v = self.args.get(k)
 610            if mandatory and (v is None or (isinstance(v, list) and not v)):
 611                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 612
 613        if (
 614            args
 615            and isinstance(self, Func)
 616            and len(args) > len(self.arg_types)
 617            and not self.is_var_len_args
 618        ):
 619            errors.append(
 620                f"The number of provided arguments ({len(args)}) is greater than "
 621                f"the maximum number of supported arguments ({len(self.arg_types)})"
 622            )
 623
 624        return errors
 625
 626    def dump(self):
 627        """
 628        Dump this Expression to a JSON-serializable dict.
 629        """
 630        from sqlglot.serde import dump
 631
 632        return dump(self)
 633
 634    @classmethod
 635    def load(cls, obj):
 636        """
 637        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 638        """
 639        from sqlglot.serde import load
 640
 641        return load(obj)
 642
 643
 644IntoType = t.Union[
 645    str,
 646    t.Type[Expression],
 647    t.Collection[t.Union[str, t.Type[Expression]]],
 648]
 649ExpOrStr = t.Union[str, Expression]
 650
 651
 652class Condition(Expression):
 653    def and_(self, *expressions, dialect=None, **opts):
 654        """
 655        AND this condition with one or multiple expressions.
 656
 657        Example:
 658            >>> condition("x=1").and_("y=1").sql()
 659            'x = 1 AND y = 1'
 660
 661        Args:
 662            *expressions (str | Expression): the SQL code strings to parse.
 663                If an `Expression` instance is passed, it will be used as-is.
 664            dialect (str): the dialect used to parse the input expression.
 665            opts (kwargs): other options to use to parse the input expressions.
 666
 667        Returns:
 668            And: the new condition.
 669        """
 670        return and_(self, *expressions, dialect=dialect, **opts)
 671
 672    def or_(self, *expressions, dialect=None, **opts):
 673        """
 674        OR this condition with one or multiple expressions.
 675
 676        Example:
 677            >>> condition("x=1").or_("y=1").sql()
 678            'x = 1 OR y = 1'
 679
 680        Args:
 681            *expressions (str | Expression): the SQL code strings to parse.
 682                If an `Expression` instance is passed, it will be used as-is.
 683            dialect (str): the dialect used to parse the input expression.
 684            opts (kwargs): other options to use to parse the input expressions.
 685
 686        Returns:
 687            Or: the new condition.
 688        """
 689        return or_(self, *expressions, dialect=dialect, **opts)
 690
 691    def not_(self):
 692        """
 693        Wrap this condition with NOT.
 694
 695        Example:
 696            >>> condition("x=1").not_().sql()
 697            'NOT x = 1'
 698
 699        Returns:
 700            Not: the new condition.
 701        """
 702        return not_(self)
 703
 704
 705class Predicate(Condition):
 706    """Relationships like x = y, x > 1, x >= y."""
 707
 708
 709class DerivedTable(Expression):
 710    @property
 711    def alias_column_names(self):
 712        table_alias = self.args.get("alias")
 713        if not table_alias:
 714            return []
 715        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
 716        return [c.name for c in column_list]
 717
 718    @property
 719    def selects(self):
 720        alias = self.args.get("alias")
 721
 722        if alias:
 723            return alias.columns
 724        return []
 725
 726    @property
 727    def named_selects(self):
 728        return [select.output_name for select in self.selects]
 729
 730
 731class Unionable(Expression):
 732    def union(self, expression, distinct=True, dialect=None, **opts):
 733        """
 734        Builds a UNION expression.
 735
 736        Example:
 737            >>> import sqlglot
 738            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 739            'SELECT * FROM foo UNION SELECT * FROM bla'
 740
 741        Args:
 742            expression (str | Expression): the SQL code string.
 743                If an `Expression` instance is passed, it will be used as-is.
 744            distinct (bool): set the DISTINCT flag if and only if this is true.
 745            dialect (str): the dialect used to parse the input expression.
 746            opts (kwargs): other options to use to parse the input expressions.
 747        Returns:
 748            Union: the Union expression.
 749        """
 750        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 751
 752    def intersect(self, expression, distinct=True, dialect=None, **opts):
 753        """
 754        Builds an INTERSECT expression.
 755
 756        Example:
 757            >>> import sqlglot
 758            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 759            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 760
 761        Args:
 762            expression (str | Expression): the SQL code string.
 763                If an `Expression` instance is passed, it will be used as-is.
 764            distinct (bool): set the DISTINCT flag if and only if this is true.
 765            dialect (str): the dialect used to parse the input expression.
 766            opts (kwargs): other options to use to parse the input expressions.
 767        Returns:
 768            Intersect: the Intersect expression
 769        """
 770        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 771
 772    def except_(self, expression, distinct=True, dialect=None, **opts):
 773        """
 774        Builds an EXCEPT expression.
 775
 776        Example:
 777            >>> import sqlglot
 778            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 779            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 780
 781        Args:
 782            expression (str | Expression): the SQL code string.
 783                If an `Expression` instance is passed, it will be used as-is.
 784            distinct (bool): set the DISTINCT flag if and only if this is true.
 785            dialect (str): the dialect used to parse the input expression.
 786            opts (kwargs): other options to use to parse the input expressions.
 787        Returns:
 788            Except: the Except expression
 789        """
 790        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 791
 792
 793class UDTF(DerivedTable, Unionable):
 794    pass
 795
 796
 797class Cache(Expression):
 798    arg_types = {
 799        "with": False,
 800        "this": True,
 801        "lazy": False,
 802        "options": False,
 803        "expression": False,
 804    }
 805
 806
 807class Uncache(Expression):
 808    arg_types = {"this": True, "exists": False}
 809
 810
 811class Create(Expression):
 812    arg_types = {
 813        "with": False,
 814        "this": True,
 815        "kind": True,
 816        "expression": False,
 817        "exists": False,
 818        "properties": False,
 819        "replace": False,
 820        "unique": False,
 821        "volatile": False,
 822        "indexes": False,
 823        "no_schema_binding": False,
 824        "begin": False,
 825    }
 826
 827
 828class Describe(Expression):
 829    arg_types = {"this": True, "kind": False}
 830
 831
 832class Pragma(Expression):
 833    pass
 834
 835
 836class Set(Expression):
 837    arg_types = {"expressions": False}
 838
 839
 840class SetItem(Expression):
 841    arg_types = {
 842        "this": False,
 843        "expressions": False,
 844        "kind": False,
 845        "collate": False,  # MySQL SET NAMES statement
 846        "global": False,
 847    }
 848
 849
 850class Show(Expression):
 851    arg_types = {
 852        "this": True,
 853        "target": False,
 854        "offset": False,
 855        "limit": False,
 856        "like": False,
 857        "where": False,
 858        "db": False,
 859        "full": False,
 860        "mutex": False,
 861        "query": False,
 862        "channel": False,
 863        "global": False,
 864        "log": False,
 865        "position": False,
 866        "types": False,
 867    }
 868
 869
 870class UserDefinedFunction(Expression):
 871    arg_types = {"this": True, "expressions": False, "wrapped": False}
 872
 873
 874class CharacterSet(Expression):
 875    arg_types = {"this": True, "default": False}
 876
 877
 878class With(Expression):
 879    arg_types = {"expressions": True, "recursive": False}
 880
 881    @property
 882    def recursive(self) -> bool:
 883        return bool(self.args.get("recursive"))
 884
 885
 886class WithinGroup(Expression):
 887    arg_types = {"this": True, "expression": False}
 888
 889
 890class CTE(DerivedTable):
 891    arg_types = {"this": True, "alias": True}
 892
 893
 894class TableAlias(Expression):
 895    arg_types = {"this": False, "columns": False}
 896
 897    @property
 898    def columns(self):
 899        return self.args.get("columns") or []
 900
 901
 902class BitString(Condition):
 903    pass
 904
 905
 906class HexString(Condition):
 907    pass
 908
 909
 910class ByteString(Condition):
 911    pass
 912
 913
 914class Column(Condition):
 915    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
 916
 917    @property
 918    def table(self) -> str:
 919        return self.text("table")
 920
 921    @property
 922    def db(self) -> str:
 923        return self.text("db")
 924
 925    @property
 926    def catalog(self) -> str:
 927        return self.text("catalog")
 928
 929    @property
 930    def output_name(self) -> str:
 931        return self.name
 932
 933    @property
 934    def parts(self) -> t.List[Identifier]:
 935        """Return the parts of a column in order catalog, db, table, name."""
 936        return [part for part in reversed(list(self.args.values())) if part]
 937
 938    def to_dot(self) -> Dot:
 939        """Converts the column into a dot expression."""
 940        parts = self.parts
 941        parent = self.parent
 942
 943        while parent:
 944            if isinstance(parent, Dot):
 945                parts.append(parent.expression)
 946            parent = parent.parent
 947
 948        return Dot.build(parts)
 949
 950
 951class ColumnPosition(Expression):
 952    arg_types = {"this": False, "position": True}
 953
 954
 955class ColumnDef(Expression):
 956    arg_types = {
 957        "this": True,
 958        "kind": False,
 959        "constraints": False,
 960        "exists": False,
 961        "position": False,
 962    }
 963
 964
 965class AlterColumn(Expression):
 966    arg_types = {
 967        "this": True,
 968        "dtype": False,
 969        "collate": False,
 970        "using": False,
 971        "default": False,
 972        "drop": False,
 973    }
 974
 975
 976class RenameTable(Expression):
 977    pass
 978
 979
 980class SetTag(Expression):
 981    arg_types = {"expressions": True, "unset": False}
 982
 983
 984class Comment(Expression):
 985    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
 986
 987
 988class ColumnConstraint(Expression):
 989    arg_types = {"this": False, "kind": True}
 990
 991
 992class ColumnConstraintKind(Expression):
 993    pass
 994
 995
 996class AutoIncrementColumnConstraint(ColumnConstraintKind):
 997    pass
 998
 999
1000class CaseSpecificColumnConstraint(ColumnConstraintKind):
1001    arg_types = {"not_": True}
1002
1003
1004class CharacterSetColumnConstraint(ColumnConstraintKind):
1005    arg_types = {"this": True}
1006
1007
1008class CheckColumnConstraint(ColumnConstraintKind):
1009    pass
1010
1011
1012class CollateColumnConstraint(ColumnConstraintKind):
1013    pass
1014
1015
1016class CommentColumnConstraint(ColumnConstraintKind):
1017    pass
1018
1019
1020class CompressColumnConstraint(ColumnConstraintKind):
1021    pass
1022
1023
1024class DateFormatColumnConstraint(ColumnConstraintKind):
1025    arg_types = {"this": True}
1026
1027
1028class DefaultColumnConstraint(ColumnConstraintKind):
1029    pass
1030
1031
1032class EncodeColumnConstraint(ColumnConstraintKind):
1033    pass
1034
1035
1036class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1037    # this: True -> ALWAYS, this: False -> BY DEFAULT
1038    arg_types = {
1039        "this": False,
1040        "start": False,
1041        "increment": False,
1042        "minvalue": False,
1043        "maxvalue": False,
1044        "cycle": False,
1045    }
1046
1047
1048class InlineLengthColumnConstraint(ColumnConstraintKind):
1049    pass
1050
1051
1052class NotNullColumnConstraint(ColumnConstraintKind):
1053    arg_types = {"allow_null": False}
1054
1055
1056class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1057    arg_types = {"desc": False}
1058
1059
1060class TitleColumnConstraint(ColumnConstraintKind):
1061    pass
1062
1063
1064class UniqueColumnConstraint(ColumnConstraintKind):
1065    arg_types: t.Dict[str, t.Any] = {}
1066
1067
1068class UppercaseColumnConstraint(ColumnConstraintKind):
1069    arg_types: t.Dict[str, t.Any] = {}
1070
1071
1072class PathColumnConstraint(ColumnConstraintKind):
1073    pass
1074
1075
1076class Constraint(Expression):
1077    arg_types = {"this": True, "expressions": True}
1078
1079
1080class Delete(Expression):
1081    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1082
1083    def delete(
1084        self,
1085        table: ExpOrStr,
1086        dialect: DialectType = None,
1087        copy: bool = True,
1088        **opts,
1089    ) -> Delete:
1090        """
1091        Create a DELETE expression or replace the table on an existing DELETE expression.
1092
1093        Example:
1094            >>> delete("tbl").sql()
1095            'DELETE FROM tbl'
1096
1097        Args:
1098            table: the table from which to delete.
1099            dialect: the dialect used to parse the input expression.
1100            copy: if `False`, modify this expression instance in-place.
1101            opts: other options to use to parse the input expressions.
1102
1103        Returns:
1104            Delete: the modified expression.
1105        """
1106        return _apply_builder(
1107            expression=table,
1108            instance=self,
1109            arg="this",
1110            dialect=dialect,
1111            into=Table,
1112            copy=copy,
1113            **opts,
1114        )
1115
1116    def where(
1117        self,
1118        *expressions: ExpOrStr,
1119        append: bool = True,
1120        dialect: DialectType = None,
1121        copy: bool = True,
1122        **opts,
1123    ) -> Delete:
1124        """
1125        Append to or set the WHERE expressions.
1126
1127        Example:
1128            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1129            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1130
1131        Args:
1132            *expressions: the SQL code strings to parse.
1133                If an `Expression` instance is passed, it will be used as-is.
1134                Multiple expressions are combined with an AND operator.
1135            append: if `True`, AND the new expressions to any existing expression.
1136                Otherwise, this resets the expression.
1137            dialect: the dialect used to parse the input expressions.
1138            copy: if `False`, modify this expression instance in-place.
1139            opts: other options to use to parse the input expressions.
1140
1141        Returns:
1142            Delete: the modified expression.
1143        """
1144        return _apply_conjunction_builder(
1145            *expressions,
1146            instance=self,
1147            arg="where",
1148            append=append,
1149            into=Where,
1150            dialect=dialect,
1151            copy=copy,
1152            **opts,
1153        )
1154
1155    def returning(
1156        self,
1157        expression: ExpOrStr,
1158        dialect: DialectType = None,
1159        copy: bool = True,
1160        **opts,
1161    ) -> Delete:
1162        """
1163        Set the RETURNING expression. Not supported by all dialects.
1164
1165        Example:
1166            >>> delete("tbl").returning("*", dialect="postgres").sql()
1167            'DELETE FROM tbl RETURNING *'
1168
1169        Args:
1170            expression: the SQL code strings to parse.
1171                If an `Expression` instance is passed, it will be used as-is.
1172            dialect: the dialect used to parse the input expressions.
1173            copy: if `False`, modify this expression instance in-place.
1174            opts: other options to use to parse the input expressions.
1175
1176        Returns:
1177            Delete: the modified expression.
1178        """
1179        return _apply_builder(
1180            expression=expression,
1181            instance=self,
1182            arg="returning",
1183            prefix="RETURNING",
1184            dialect=dialect,
1185            copy=copy,
1186            into=Returning,
1187            **opts,
1188        )
1189
1190
1191class Drop(Expression):
1192    arg_types = {
1193        "this": False,
1194        "kind": False,
1195        "exists": False,
1196        "temporary": False,
1197        "materialized": False,
1198        "cascade": False,
1199        "constraints": False,
1200        "purge": False,
1201    }
1202
1203
1204class Filter(Expression):
1205    arg_types = {"this": True, "expression": True}
1206
1207
1208class Check(Expression):
1209    pass
1210
1211
1212class Directory(Expression):
1213    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1214    arg_types = {"this": True, "local": False, "row_format": False}
1215
1216
1217class ForeignKey(Expression):
1218    arg_types = {
1219        "expressions": True,
1220        "reference": False,
1221        "delete": False,
1222        "update": False,
1223    }
1224
1225
1226class PrimaryKey(Expression):
1227    arg_types = {"expressions": True, "options": False}
1228
1229
1230class Unique(Expression):
1231    arg_types = {"expressions": True}
1232
1233
1234# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1235# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1236class Into(Expression):
1237    arg_types = {"this": True, "temporary": False, "unlogged": False}
1238
1239
1240class From(Expression):
1241    arg_types = {"expressions": True}
1242
1243
1244class Having(Expression):
1245    pass
1246
1247
1248class Hint(Expression):
1249    arg_types = {"expressions": True}
1250
1251
1252class JoinHint(Expression):
1253    arg_types = {"this": True, "expressions": True}
1254
1255
1256class Identifier(Expression):
1257    arg_types = {"this": True, "quoted": False}
1258
1259    @property
1260    def quoted(self):
1261        return bool(self.args.get("quoted"))
1262
1263    @property
1264    def hashable_args(self) -> t.Any:
1265        if self.quoted and any(char.isupper() for char in self.this):
1266            return (self.this, self.quoted)
1267        return self.this.lower()
1268
1269    @property
1270    def output_name(self):
1271        return self.name
1272
1273
1274class Index(Expression):
1275    arg_types = {
1276        "this": False,
1277        "table": False,
1278        "where": False,
1279        "columns": False,
1280        "unique": False,
1281        "primary": False,
1282        "amp": False,  # teradata
1283    }
1284
1285
1286class Insert(Expression):
1287    arg_types = {
1288        "with": False,
1289        "this": True,
1290        "expression": False,
1291        "returning": False,
1292        "overwrite": False,
1293        "exists": False,
1294        "partition": False,
1295        "alternative": False,
1296    }
1297
1298
1299class Returning(Expression):
1300    arg_types = {"expressions": True}
1301
1302
1303# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1304class Introducer(Expression):
1305    arg_types = {"this": True, "expression": True}
1306
1307
1308# national char, like n'utf8'
1309class National(Expression):
1310    pass
1311
1312
1313class LoadData(Expression):
1314    arg_types = {
1315        "this": True,
1316        "local": False,
1317        "overwrite": False,
1318        "inpath": True,
1319        "partition": False,
1320        "input_format": False,
1321        "serde": False,
1322    }
1323
1324
1325class Partition(Expression):
1326    arg_types = {"expressions": True}
1327
1328
1329class Fetch(Expression):
1330    arg_types = {"direction": False, "count": False}
1331
1332
1333class Group(Expression):
1334    arg_types = {
1335        "expressions": False,
1336        "grouping_sets": False,
1337        "cube": False,
1338        "rollup": False,
1339    }
1340
1341
1342class Lambda(Expression):
1343    arg_types = {"this": True, "expressions": True}
1344
1345
1346class Limit(Expression):
1347    arg_types = {"this": False, "expression": True}
1348
1349
1350class Literal(Condition):
1351    arg_types = {"this": True, "is_string": True}
1352
1353    @property
1354    def hashable_args(self) -> t.Any:
1355        return (self.this, self.args.get("is_string"))
1356
1357    @classmethod
1358    def number(cls, number) -> Literal:
1359        return cls(this=str(number), is_string=False)
1360
1361    @classmethod
1362    def string(cls, string) -> Literal:
1363        return cls(this=str(string), is_string=True)
1364
1365    @property
1366    def output_name(self):
1367        return self.name
1368
1369
1370class Join(Expression):
1371    arg_types = {
1372        "this": True,
1373        "on": False,
1374        "side": False,
1375        "kind": False,
1376        "using": False,
1377        "natural": False,
1378    }
1379
1380    @property
1381    def kind(self):
1382        return self.text("kind").upper()
1383
1384    @property
1385    def side(self):
1386        return self.text("side").upper()
1387
1388    @property
1389    def alias_or_name(self):
1390        return self.this.alias_or_name
1391
1392    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393        """
1394        Append to or set the ON expressions.
1395
1396        Example:
1397            >>> import sqlglot
1398            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1399            'JOIN x ON y = 1'
1400
1401        Args:
1402            *expressions (str | Expression): the SQL code strings to parse.
1403                If an `Expression` instance is passed, it will be used as-is.
1404                Multiple expressions are combined with an AND operator.
1405            append (bool): if `True`, AND the new expressions to any existing expression.
1406                Otherwise, this resets the expression.
1407            dialect (str): the dialect used to parse the input expressions.
1408            copy (bool): if `False`, modify this expression instance in-place.
1409            opts (kwargs): other options to use to parse the input expressions.
1410
1411        Returns:
1412            Join: the modified join expression.
1413        """
1414        join = _apply_conjunction_builder(
1415            *expressions,
1416            instance=self,
1417            arg="on",
1418            append=append,
1419            dialect=dialect,
1420            copy=copy,
1421            **opts,
1422        )
1423
1424        if join.kind == "CROSS":
1425            join.set("kind", None)
1426
1427        return join
1428
1429    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1430        """
1431        Append to or set the USING expressions.
1432
1433        Example:
1434            >>> import sqlglot
1435            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1436            'JOIN x USING (foo, bla)'
1437
1438        Args:
1439            *expressions (str | Expression): the SQL code strings to parse.
1440                If an `Expression` instance is passed, it will be used as-is.
1441            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1442                Otherwise, this resets the expression.
1443            dialect (str): the dialect used to parse the input expressions.
1444            copy (bool): if `False`, modify this expression instance in-place.
1445            opts (kwargs): other options to use to parse the input expressions.
1446
1447        Returns:
1448            Join: the modified join expression.
1449        """
1450        join = _apply_list_builder(
1451            *expressions,
1452            instance=self,
1453            arg="using",
1454            append=append,
1455            dialect=dialect,
1456            copy=copy,
1457            **opts,
1458        )
1459
1460        if join.kind == "CROSS":
1461            join.set("kind", None)
1462
1463        return join
1464
1465
1466class Lateral(UDTF):
1467    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1468
1469
1470class MatchRecognize(Expression):
1471    arg_types = {
1472        "partition_by": False,
1473        "order": False,
1474        "measures": False,
1475        "rows": False,
1476        "after": False,
1477        "pattern": False,
1478        "define": False,
1479    }
1480
1481
1482# Clickhouse FROM FINAL modifier
1483# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1484class Final(Expression):
1485    pass
1486
1487
1488class Offset(Expression):
1489    arg_types = {"this": False, "expression": True}
1490
1491
1492class Order(Expression):
1493    arg_types = {"this": False, "expressions": True}
1494
1495
1496# hive specific sorts
1497# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1498class Cluster(Order):
1499    pass
1500
1501
1502class Distribute(Order):
1503    pass
1504
1505
1506class Sort(Order):
1507    pass
1508
1509
1510class Ordered(Expression):
1511    arg_types = {"this": True, "desc": True, "nulls_first": True}
1512
1513
1514class Property(Expression):
1515    arg_types = {"this": True, "value": True}
1516
1517
1518class AfterJournalProperty(Property):
1519    arg_types = {"no": True, "dual": False, "local": False}
1520
1521
1522class AlgorithmProperty(Property):
1523    arg_types = {"this": True}
1524
1525
1526class AutoIncrementProperty(Property):
1527    arg_types = {"this": True}
1528
1529
1530class BlockCompressionProperty(Property):
1531    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1532
1533
1534class CharacterSetProperty(Property):
1535    arg_types = {"this": True, "default": True}
1536
1537
1538class ChecksumProperty(Property):
1539    arg_types = {"on": False, "default": False}
1540
1541
1542class CollateProperty(Property):
1543    arg_types = {"this": True}
1544
1545
1546class DataBlocksizeProperty(Property):
1547    arg_types = {"size": False, "units": False, "min": False, "default": False}
1548
1549
1550class DefinerProperty(Property):
1551    arg_types = {"this": True}
1552
1553
1554class DistKeyProperty(Property):
1555    arg_types = {"this": True}
1556
1557
1558class DistStyleProperty(Property):
1559    arg_types = {"this": True}
1560
1561
1562class EngineProperty(Property):
1563    arg_types = {"this": True}
1564
1565
1566class ExecuteAsProperty(Property):
1567    arg_types = {"this": True}
1568
1569
1570class ExternalProperty(Property):
1571    arg_types = {"this": False}
1572
1573
1574class FallbackProperty(Property):
1575    arg_types = {"no": True, "protection": False}
1576
1577
1578class FileFormatProperty(Property):
1579    arg_types = {"this": True}
1580
1581
1582class FreespaceProperty(Property):
1583    arg_types = {"this": True, "percent": False}
1584
1585
1586class InputOutputFormat(Expression):
1587    arg_types = {"input_format": False, "output_format": False}
1588
1589
1590class IsolatedLoadingProperty(Property):
1591    arg_types = {
1592        "no": True,
1593        "concurrent": True,
1594        "for_all": True,
1595        "for_insert": True,
1596        "for_none": True,
1597    }
1598
1599
1600class JournalProperty(Property):
1601    arg_types = {"no": True, "dual": False, "before": False}
1602
1603
1604class LanguageProperty(Property):
1605    arg_types = {"this": True}
1606
1607
1608class LikeProperty(Property):
1609    arg_types = {"this": True, "expressions": False}
1610
1611
1612class LocationProperty(Property):
1613    arg_types = {"this": True}
1614
1615
1616class LockingProperty(Property):
1617    arg_types = {
1618        "this": False,
1619        "kind": True,
1620        "for_or_in": True,
1621        "lock_type": True,
1622        "override": False,
1623    }
1624
1625
1626class LogProperty(Property):
1627    arg_types = {"no": True}
1628
1629
1630class MaterializedProperty(Property):
1631    arg_types = {"this": False}
1632
1633
1634class MergeBlockRatioProperty(Property):
1635    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1636
1637
1638class NoPrimaryIndexProperty(Property):
1639    arg_types = {"this": False}
1640
1641
1642class OnCommitProperty(Property):
1643    arg_type = {"this": False}
1644
1645
1646class PartitionedByProperty(Property):
1647    arg_types = {"this": True}
1648
1649
1650class ReturnsProperty(Property):
1651    arg_types = {"this": True, "is_table": False, "table": False}
1652
1653
1654class RowFormatDelimitedProperty(Property):
1655    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1656    arg_types = {
1657        "fields": False,
1658        "escaped": False,
1659        "collection_items": False,
1660        "map_keys": False,
1661        "lines": False,
1662        "null": False,
1663        "serde": False,
1664    }
1665
1666
1667class RowFormatSerdeProperty(Property):
1668    arg_types = {"this": True}
1669
1670
1671class SchemaCommentProperty(Property):
1672    arg_types = {"this": True}
1673
1674
1675class SerdeProperties(Property):
1676    arg_types = {"expressions": True}
1677
1678
1679class SetProperty(Property):
1680    arg_types = {"multi": True}
1681
1682
1683class SortKeyProperty(Property):
1684    arg_types = {"this": True, "compound": False}
1685
1686
1687class SqlSecurityProperty(Property):
1688    arg_types = {"definer": True}
1689
1690
1691class TableFormatProperty(Property):
1692    arg_types = {"this": True}
1693
1694
1695class TemporaryProperty(Property):
1696    arg_types = {"global_": True}
1697
1698
1699class TransientProperty(Property):
1700    arg_types = {"this": False}
1701
1702
1703class VolatilityProperty(Property):
1704    arg_types = {"this": True}
1705
1706
1707class WithDataProperty(Property):
1708    arg_types = {"no": True, "statistics": False}
1709
1710
1711class WithJournalTableProperty(Property):
1712    arg_types = {"this": True}
1713
1714
1715class Properties(Expression):
1716    arg_types = {"expressions": True}
1717
1718    NAME_TO_PROPERTY = {
1719        "ALGORITHM": AlgorithmProperty,
1720        "AUTO_INCREMENT": AutoIncrementProperty,
1721        "CHARACTER SET": CharacterSetProperty,
1722        "COLLATE": CollateProperty,
1723        "COMMENT": SchemaCommentProperty,
1724        "DEFINER": DefinerProperty,
1725        "DISTKEY": DistKeyProperty,
1726        "DISTSTYLE": DistStyleProperty,
1727        "ENGINE": EngineProperty,
1728        "EXECUTE AS": ExecuteAsProperty,
1729        "FORMAT": FileFormatProperty,
1730        "LANGUAGE": LanguageProperty,
1731        "LOCATION": LocationProperty,
1732        "PARTITIONED_BY": PartitionedByProperty,
1733        "RETURNS": ReturnsProperty,
1734        "SORTKEY": SortKeyProperty,
1735        "TABLE_FORMAT": TableFormatProperty,
1736    }
1737
1738    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1739
1740    # CREATE property locations
1741    # Form: schema specified
1742    #   create [POST_CREATE]
1743    #     table a [POST_NAME]
1744    #     (b int) [POST_SCHEMA]
1745    #     with ([POST_WITH])
1746    #     index (b) [POST_INDEX]
1747    #
1748    # Form: alias selection
1749    #   create [POST_CREATE]
1750    #     table a [POST_NAME]
1751    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1752    #     index (c) [POST_INDEX]
1753    class Location(AutoName):
1754        POST_CREATE = auto()
1755        POST_NAME = auto()
1756        POST_SCHEMA = auto()
1757        POST_WITH = auto()
1758        POST_ALIAS = auto()
1759        POST_EXPRESSION = auto()
1760        POST_INDEX = auto()
1761        UNSUPPORTED = auto()
1762
1763    @classmethod
1764    def from_dict(cls, properties_dict) -> Properties:
1765        expressions = []
1766        for key, value in properties_dict.items():
1767            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1768            if property_cls:
1769                expressions.append(property_cls(this=convert(value)))
1770            else:
1771                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1772
1773        return cls(expressions=expressions)
1774
1775
1776class Qualify(Expression):
1777    pass
1778
1779
1780# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
1781class Return(Expression):
1782    pass
1783
1784
1785class Reference(Expression):
1786    arg_types = {"this": True, "expressions": False, "options": False}
1787
1788
1789class Tuple(Expression):
1790    arg_types = {"expressions": False}
1791
1792
1793class Subqueryable(Unionable):
1794    def subquery(self, alias=None, copy=True) -> Subquery:
1795        """
1796        Convert this expression to an aliased expression that can be used as a Subquery.
1797
1798        Example:
1799            >>> subquery = Select().select("x").from_("tbl").subquery()
1800            >>> Select().select("x").from_(subquery).sql()
1801            'SELECT x FROM (SELECT x FROM tbl)'
1802
1803        Args:
1804            alias (str | Identifier): an optional alias for the subquery
1805            copy (bool): if `False`, modify this expression instance in-place.
1806
1807        Returns:
1808            Alias: the subquery
1809        """
1810        instance = _maybe_copy(self, copy)
1811        return Subquery(
1812            this=instance,
1813            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1814        )
1815
1816    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1817        raise NotImplementedError
1818
1819    @property
1820    def ctes(self):
1821        with_ = self.args.get("with")
1822        if not with_:
1823            return []
1824        return with_.expressions
1825
1826    @property
1827    def selects(self):
1828        raise NotImplementedError("Subqueryable objects must implement `selects`")
1829
1830    @property
1831    def named_selects(self):
1832        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1833
1834    def with_(
1835        self,
1836        alias,
1837        as_,
1838        recursive=None,
1839        append=True,
1840        dialect=None,
1841        copy=True,
1842        **opts,
1843    ):
1844        """
1845        Append to or set the common table expressions.
1846
1847        Example:
1848            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1849            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1850
1851        Args:
1852            alias (str | Expression): the SQL code string to parse as the table name.
1853                If an `Expression` instance is passed, this is used as-is.
1854            as_ (str | Expression): the SQL code string to parse as the table expression.
1855                If an `Expression` instance is passed, it will be used as-is.
1856            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1857            append (bool): if `True`, add to any existing expressions.
1858                Otherwise, this resets the expressions.
1859            dialect (str): the dialect used to parse the input expression.
1860            copy (bool): if `False`, modify this expression instance in-place.
1861            opts (kwargs): other options to use to parse the input expressions.
1862
1863        Returns:
1864            Select: the modified expression.
1865        """
1866        alias_expression = maybe_parse(
1867            alias,
1868            dialect=dialect,
1869            into=TableAlias,
1870            **opts,
1871        )
1872        as_expression = maybe_parse(
1873            as_,
1874            dialect=dialect,
1875            **opts,
1876        )
1877        cte = CTE(
1878            this=as_expression,
1879            alias=alias_expression,
1880        )
1881        return _apply_child_list_builder(
1882            cte,
1883            instance=self,
1884            arg="with",
1885            append=append,
1886            copy=copy,
1887            into=With,
1888            properties={"recursive": recursive or False},
1889        )
1890
1891
1892QUERY_MODIFIERS = {
1893    "match": False,
1894    "laterals": False,
1895    "joins": False,
1896    "pivots": False,
1897    "where": False,
1898    "group": False,
1899    "having": False,
1900    "qualify": False,
1901    "windows": False,
1902    "distribute": False,
1903    "sort": False,
1904    "cluster": False,
1905    "order": False,
1906    "limit": False,
1907    "offset": False,
1908    "lock": False,
1909    "sample": False,
1910}
1911
1912
1913class Table(Expression):
1914    arg_types = {
1915        "this": True,
1916        "alias": False,
1917        "db": False,
1918        "catalog": False,
1919        "laterals": False,
1920        "joins": False,
1921        "pivots": False,
1922        "hints": False,
1923        "system_time": False,
1924    }
1925
1926    @property
1927    def db(self) -> str:
1928        return self.text("db")
1929
1930    @property
1931    def catalog(self) -> str:
1932        return self.text("catalog")
1933
1934
1935# See the TSQL "Querying data in a system-versioned temporal table" page
1936class SystemTime(Expression):
1937    arg_types = {
1938        "this": False,
1939        "expression": False,
1940        "kind": True,
1941    }
1942
1943
1944class Union(Subqueryable):
1945    arg_types = {
1946        "with": False,
1947        "this": True,
1948        "expression": True,
1949        "distinct": False,
1950        **QUERY_MODIFIERS,
1951    }
1952
1953    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1954        """
1955        Set the LIMIT expression.
1956
1957        Example:
1958            >>> select("1").union(select("1")).limit(1).sql()
1959            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1960
1961        Args:
1962            expression (str | int | Expression): the SQL code string to parse.
1963                This can also be an integer.
1964                If a `Limit` instance is passed, this is used as-is.
1965                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1966            dialect (str): the dialect used to parse the input expression.
1967            copy (bool): if `False`, modify this expression instance in-place.
1968            opts (kwargs): other options to use to parse the input expressions.
1969
1970        Returns:
1971            Select: The limited subqueryable.
1972        """
1973        return (
1974            select("*")
1975            .from_(self.subquery(alias="_l_0", copy=copy))
1976            .limit(expression, dialect=dialect, copy=False, **opts)
1977        )
1978
1979    def select(
1980        self,
1981        *expressions: ExpOrStr,
1982        append: bool = True,
1983        dialect: DialectType = None,
1984        copy: bool = True,
1985        **opts,
1986    ) -> Union:
1987        """Append to or set the SELECT of the union recursively.
1988
1989        Example:
1990            >>> from sqlglot import parse_one
1991            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1992            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1993
1994        Args:
1995            *expressions: the SQL code strings to parse.
1996                If an `Expression` instance is passed, it will be used as-is.
1997            append: if `True`, add to any existing expressions.
1998                Otherwise, this resets the expressions.
1999            dialect: the dialect used to parse the input expressions.
2000            copy: if `False`, modify this expression instance in-place.
2001            opts: other options to use to parse the input expressions.
2002
2003        Returns:
2004            Union: the modified expression.
2005        """
2006        this = self.copy() if copy else self
2007        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2008        this.expression.unnest().select(
2009            *expressions, append=append, dialect=dialect, copy=False, **opts
2010        )
2011        return this
2012
2013    @property
2014    def named_selects(self):
2015        return self.this.unnest().named_selects
2016
2017    @property
2018    def is_star(self) -> bool:
2019        return self.this.is_star or self.expression.is_star
2020
2021    @property
2022    def selects(self):
2023        return self.this.unnest().selects
2024
2025    @property
2026    def left(self):
2027        return self.this
2028
2029    @property
2030    def right(self):
2031        return self.expression
2032
2033
2034class Except(Union):
2035    pass
2036
2037
2038class Intersect(Union):
2039    pass
2040
2041
2042class Unnest(UDTF):
2043    arg_types = {
2044        "expressions": True,
2045        "ordinality": False,
2046        "alias": False,
2047        "offset": False,
2048    }
2049
2050
2051class Update(Expression):
2052    arg_types = {
2053        "with": False,
2054        "this": False,
2055        "expressions": True,
2056        "from": False,
2057        "where": False,
2058        "returning": False,
2059    }
2060
2061
2062class Values(UDTF):
2063    arg_types = {
2064        "expressions": True,
2065        "ordinality": False,
2066        "alias": False,
2067    }
2068
2069
2070class Var(Expression):
2071    pass
2072
2073
2074class Schema(Expression):
2075    arg_types = {"this": False, "expressions": False}
2076
2077
2078# Used to represent the FOR UPDATE and FOR SHARE locking read types.
2079# https://dev.mysql.com/doc/refman/8.0/en/innodb-locking-reads.html
2080class Lock(Expression):
2081    arg_types = {"update": True}
2082
2083
2084class Select(Subqueryable):
2085    arg_types = {
2086        "with": False,
2087        "kind": False,
2088        "expressions": False,
2089        "hint": False,
2090        "distinct": False,
2091        "into": False,
2092        "from": False,
2093        **QUERY_MODIFIERS,
2094    }
2095
2096    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2097        """
2098        Set the FROM expression.
2099
2100        Example:
2101            >>> Select().from_("tbl").select("x").sql()
2102            'SELECT x FROM tbl'
2103
2104        Args:
2105            *expressions (str | Expression): the SQL code strings to parse.
2106                If a `From` instance is passed, this is used as-is.
2107                If another `Expression` instance is passed, it will be wrapped in a `From`.
2108            append (bool): if `True`, add to any existing expressions.
2109                Otherwise, this flattens all the `From` expression into a single expression.
2110            dialect (str): the dialect used to parse the input expression.
2111            copy (bool): if `False`, modify this expression instance in-place.
2112            opts (kwargs): other options to use to parse the input expressions.
2113
2114        Returns:
2115            Select: the modified expression.
2116        """
2117        return _apply_child_list_builder(
2118            *expressions,
2119            instance=self,
2120            arg="from",
2121            append=append,
2122            copy=copy,
2123            prefix="FROM",
2124            into=From,
2125            dialect=dialect,
2126            **opts,
2127        )
2128
2129    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2130        """
2131        Set the GROUP BY expression.
2132
2133        Example:
2134            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2135            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2136
2137        Args:
2138            *expressions (str | Expression): the SQL code strings to parse.
2139                If a `Group` instance is passed, this is used as-is.
2140                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2141                If nothing is passed in then a group by is not applied to the expression
2142            append (bool): if `True`, add to any existing expressions.
2143                Otherwise, this flattens all the `Group` expression into a single expression.
2144            dialect (str): the dialect used to parse the input expression.
2145            copy (bool): if `False`, modify this expression instance in-place.
2146            opts (kwargs): other options to use to parse the input expressions.
2147
2148        Returns:
2149            Select: the modified expression.
2150        """
2151        if not expressions:
2152            return self if not copy else self.copy()
2153        return _apply_child_list_builder(
2154            *expressions,
2155            instance=self,
2156            arg="group",
2157            append=append,
2158            copy=copy,
2159            prefix="GROUP BY",
2160            into=Group,
2161            dialect=dialect,
2162            **opts,
2163        )
2164
2165    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2166        """
2167        Set the ORDER BY expression.
2168
2169        Example:
2170            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2171            'SELECT x FROM tbl ORDER BY x DESC'
2172
2173        Args:
2174            *expressions (str | Expression): the SQL code strings to parse.
2175                If a `Group` instance is passed, this is used as-is.
2176                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2177            append (bool): if `True`, add to any existing expressions.
2178                Otherwise, this flattens all the `Order` expression into a single expression.
2179            dialect (str): the dialect used to parse the input expression.
2180            copy (bool): if `False`, modify this expression instance in-place.
2181            opts (kwargs): other options to use to parse the input expressions.
2182
2183        Returns:
2184            Select: the modified expression.
2185        """
2186        return _apply_child_list_builder(
2187            *expressions,
2188            instance=self,
2189            arg="order",
2190            append=append,
2191            copy=copy,
2192            prefix="ORDER BY",
2193            into=Order,
2194            dialect=dialect,
2195            **opts,
2196        )
2197
2198    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2199        """
2200        Set the SORT BY expression.
2201
2202        Example:
2203            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2204            'SELECT x FROM tbl SORT BY x DESC'
2205
2206        Args:
2207            *expressions (str | Expression): the SQL code strings to parse.
2208                If a `Group` instance is passed, this is used as-is.
2209                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2210            append (bool): if `True`, add to any existing expressions.
2211                Otherwise, this flattens all the `Order` expression into a single expression.
2212            dialect (str): the dialect used to parse the input expression.
2213            copy (bool): if `False`, modify this expression instance in-place.
2214            opts (kwargs): other options to use to parse the input expressions.
2215
2216        Returns:
2217            Select: the modified expression.
2218        """
2219        return _apply_child_list_builder(
2220            *expressions,
2221            instance=self,
2222            arg="sort",
2223            append=append,
2224            copy=copy,
2225            prefix="SORT BY",
2226            into=Sort,
2227            dialect=dialect,
2228            **opts,
2229        )
2230
2231    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2232        """
2233        Set the CLUSTER BY expression.
2234
2235        Example:
2236            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2237            'SELECT x FROM tbl CLUSTER BY x DESC'
2238
2239        Args:
2240            *expressions (str | Expression): the SQL code strings to parse.
2241                If a `Group` instance is passed, this is used as-is.
2242                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2243            append (bool): if `True`, add to any existing expressions.
2244                Otherwise, this flattens all the `Order` expression into a single expression.
2245            dialect (str): the dialect used to parse the input expression.
2246            copy (bool): if `False`, modify this expression instance in-place.
2247            opts (kwargs): other options to use to parse the input expressions.
2248
2249        Returns:
2250            Select: the modified expression.
2251        """
2252        return _apply_child_list_builder(
2253            *expressions,
2254            instance=self,
2255            arg="cluster",
2256            append=append,
2257            copy=copy,
2258            prefix="CLUSTER BY",
2259            into=Cluster,
2260            dialect=dialect,
2261            **opts,
2262        )
2263
2264    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2265        """
2266        Set the LIMIT expression.
2267
2268        Example:
2269            >>> Select().from_("tbl").select("x").limit(10).sql()
2270            'SELECT x FROM tbl LIMIT 10'
2271
2272        Args:
2273            expression (str | int | Expression): the SQL code string to parse.
2274                This can also be an integer.
2275                If a `Limit` instance is passed, this is used as-is.
2276                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2277            dialect (str): the dialect used to parse the input expression.
2278            copy (bool): if `False`, modify this expression instance in-place.
2279            opts (kwargs): other options to use to parse the input expressions.
2280
2281        Returns:
2282            Select: the modified expression.
2283        """
2284        return _apply_builder(
2285            expression=expression,
2286            instance=self,
2287            arg="limit",
2288            into=Limit,
2289            prefix="LIMIT",
2290            dialect=dialect,
2291            copy=copy,
2292            **opts,
2293        )
2294
2295    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2296        """
2297        Set the OFFSET expression.
2298
2299        Example:
2300            >>> Select().from_("tbl").select("x").offset(10).sql()
2301            'SELECT x FROM tbl OFFSET 10'
2302
2303        Args:
2304            expression (str | int | Expression): the SQL code string to parse.
2305                This can also be an integer.
2306                If a `Offset` instance is passed, this is used as-is.
2307                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2308            dialect (str): the dialect used to parse the input expression.
2309            copy (bool): if `False`, modify this expression instance in-place.
2310            opts (kwargs): other options to use to parse the input expressions.
2311
2312        Returns:
2313            Select: the modified expression.
2314        """
2315        return _apply_builder(
2316            expression=expression,
2317            instance=self,
2318            arg="offset",
2319            into=Offset,
2320            prefix="OFFSET",
2321            dialect=dialect,
2322            copy=copy,
2323            **opts,
2324        )
2325
2326    def select(
2327        self,
2328        *expressions: ExpOrStr,
2329        append: bool = True,
2330        dialect: DialectType = None,
2331        copy: bool = True,
2332        **opts,
2333    ) -> Select:
2334        """
2335        Append to or set the SELECT expressions.
2336
2337        Example:
2338            >>> Select().select("x", "y").sql()
2339            'SELECT x, y'
2340
2341        Args:
2342            *expressions: the SQL code strings to parse.
2343                If an `Expression` instance is passed, it will be used as-is.
2344            append: if `True`, add to any existing expressions.
2345                Otherwise, this resets the expressions.
2346            dialect: the dialect used to parse the input expressions.
2347            copy: if `False`, modify this expression instance in-place.
2348            opts: other options to use to parse the input expressions.
2349
2350        Returns:
2351            Select: the modified expression.
2352        """
2353        return _apply_list_builder(
2354            *expressions,
2355            instance=self,
2356            arg="expressions",
2357            append=append,
2358            dialect=dialect,
2359            copy=copy,
2360            **opts,
2361        )
2362
2363    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2364        """
2365        Append to or set the LATERAL expressions.
2366
2367        Example:
2368            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2369            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2370
2371        Args:
2372            *expressions (str | Expression): the SQL code strings to parse.
2373                If an `Expression` instance is passed, it will be used as-is.
2374            append (bool): if `True`, add to any existing expressions.
2375                Otherwise, this resets the expressions.
2376            dialect (str): the dialect used to parse the input expressions.
2377            copy (bool): if `False`, modify this expression instance in-place.
2378            opts (kwargs): other options to use to parse the input expressions.
2379
2380        Returns:
2381            Select: the modified expression.
2382        """
2383        return _apply_list_builder(
2384            *expressions,
2385            instance=self,
2386            arg="laterals",
2387            append=append,
2388            into=Lateral,
2389            prefix="LATERAL VIEW",
2390            dialect=dialect,
2391            copy=copy,
2392            **opts,
2393        )
2394
2395    def join(
2396        self,
2397        expression,
2398        on=None,
2399        using=None,
2400        append=True,
2401        join_type=None,
2402        join_alias=None,
2403        dialect=None,
2404        copy=True,
2405        **opts,
2406    ) -> Select:
2407        """
2408        Append to or set the JOIN expressions.
2409
2410        Example:
2411            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2412            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2413
2414            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2415            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2416
2417            Use `join_type` to change the type of join:
2418
2419            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2420            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2421
2422        Args:
2423            expression (str | Expression): the SQL code string to parse.
2424                If an `Expression` instance is passed, it will be used as-is.
2425            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2426                If an `Expression` instance is passed, it will be used as-is.
2427            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2428                If an `Expression` instance is passed, it will be used as-is.
2429            append (bool): if `True`, add to any existing expressions.
2430                Otherwise, this resets the expressions.
2431            join_type (str): If set, alter the parsed join type
2432            dialect (str): the dialect used to parse the input expressions.
2433            copy (bool): if `False`, modify this expression instance in-place.
2434            opts (kwargs): other options to use to parse the input expressions.
2435
2436        Returns:
2437            Select: the modified expression.
2438        """
2439        parse_args = {"dialect": dialect, **opts}
2440
2441        try:
2442            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2443        except ParseError:
2444            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2445
2446        join = expression if isinstance(expression, Join) else Join(this=expression)
2447
2448        if isinstance(join.this, Select):
2449            join.this.replace(join.this.subquery())
2450
2451        if join_type:
2452            natural: t.Optional[Token]
2453            side: t.Optional[Token]
2454            kind: t.Optional[Token]
2455
2456            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2457
2458            if natural:
2459                join.set("natural", True)
2460            if side:
2461                join.set("side", side.text)
2462            if kind:
2463                join.set("kind", kind.text)
2464
2465        if on:
2466            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2467            join.set("on", on)
2468
2469        if using:
2470            join = _apply_list_builder(
2471                *ensure_collection(using),
2472                instance=join,
2473                arg="using",
2474                append=append,
2475                copy=copy,
2476                **opts,
2477            )
2478
2479        if join_alias:
2480            join.set("this", alias_(join.this, join_alias, table=True))
2481        return _apply_list_builder(
2482            join,
2483            instance=self,
2484            arg="joins",
2485            append=append,
2486            copy=copy,
2487            **opts,
2488        )
2489
2490    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2491        """
2492        Append to or set the WHERE expressions.
2493
2494        Example:
2495            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2496            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2497
2498        Args:
2499            *expressions (str | Expression): the SQL code strings to parse.
2500                If an `Expression` instance is passed, it will be used as-is.
2501                Multiple expressions are combined with an AND operator.
2502            append (bool): if `True`, AND the new expressions to any existing expression.
2503                Otherwise, this resets the expression.
2504            dialect (str): the dialect used to parse the input expressions.
2505            copy (bool): if `False`, modify this expression instance in-place.
2506            opts (kwargs): other options to use to parse the input expressions.
2507
2508        Returns:
2509            Select: the modified expression.
2510        """
2511        return _apply_conjunction_builder(
2512            *expressions,
2513            instance=self,
2514            arg="where",
2515            append=append,
2516            into=Where,
2517            dialect=dialect,
2518            copy=copy,
2519            **opts,
2520        )
2521
2522    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2523        """
2524        Append to or set the HAVING expressions.
2525
2526        Example:
2527            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2528            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2529
2530        Args:
2531            *expressions (str | Expression): the SQL code strings to parse.
2532                If an `Expression` instance is passed, it will be used as-is.
2533                Multiple expressions are combined with an AND operator.
2534            append (bool): if `True`, AND the new expressions to any existing expression.
2535                Otherwise, this resets the expression.
2536            dialect (str): the dialect used to parse the input expressions.
2537            copy (bool): if `False`, modify this expression instance in-place.
2538            opts (kwargs): other options to use to parse the input expressions.
2539
2540        Returns:
2541            Select: the modified expression.
2542        """
2543        return _apply_conjunction_builder(
2544            *expressions,
2545            instance=self,
2546            arg="having",
2547            append=append,
2548            into=Having,
2549            dialect=dialect,
2550            copy=copy,
2551            **opts,
2552        )
2553
2554    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2555        return _apply_list_builder(
2556            *expressions,
2557            instance=self,
2558            arg="windows",
2559            append=append,
2560            into=Window,
2561            dialect=dialect,
2562            copy=copy,
2563            **opts,
2564        )
2565
2566    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2567        return _apply_conjunction_builder(
2568            *expressions,
2569            instance=self,
2570            arg="qualify",
2571            append=append,
2572            into=Qualify,
2573            dialect=dialect,
2574            copy=copy,
2575            **opts,
2576        )
2577
2578    def distinct(self, distinct=True, copy=True) -> Select:
2579        """
2580        Set the OFFSET expression.
2581
2582        Example:
2583            >>> Select().from_("tbl").select("x").distinct().sql()
2584            'SELECT DISTINCT x FROM tbl'
2585
2586        Args:
2587            distinct (bool): whether the Select should be distinct
2588            copy (bool): if `False`, modify this expression instance in-place.
2589
2590        Returns:
2591            Select: the modified expression.
2592        """
2593        instance = _maybe_copy(self, copy)
2594        instance.set("distinct", Distinct() if distinct else None)
2595        return instance
2596
2597    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2598        """
2599        Convert this expression to a CREATE TABLE AS statement.
2600
2601        Example:
2602            >>> Select().select("*").from_("tbl").ctas("x").sql()
2603            'CREATE TABLE x AS SELECT * FROM tbl'
2604
2605        Args:
2606            table (str | Expression): the SQL code string to parse as the table name.
2607                If another `Expression` instance is passed, it will be used as-is.
2608            properties (dict): an optional mapping of table properties
2609            dialect (str): the dialect used to parse the input table.
2610            copy (bool): if `False`, modify this expression instance in-place.
2611            opts (kwargs): other options to use to parse the input table.
2612
2613        Returns:
2614            Create: the CREATE TABLE AS expression
2615        """
2616        instance = _maybe_copy(self, copy)
2617        table_expression = maybe_parse(
2618            table,
2619            into=Table,
2620            dialect=dialect,
2621            **opts,
2622        )
2623        properties_expression = None
2624        if properties:
2625            properties_expression = Properties.from_dict(properties)
2626
2627        return Create(
2628            this=table_expression,
2629            kind="table",
2630            expression=instance,
2631            properties=properties_expression,
2632        )
2633
2634    def lock(self, update: bool = True, copy: bool = True) -> Select:
2635        """
2636        Set the locking read mode for this expression.
2637
2638        Examples:
2639            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2640            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2641
2642            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2643            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2644
2645        Args:
2646            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2647            copy: if `False`, modify this expression instance in-place.
2648
2649        Returns:
2650            The modified expression.
2651        """
2652
2653        inst = _maybe_copy(self, copy)
2654        inst.set("lock", Lock(update=update))
2655
2656        return inst
2657
2658    @property
2659    def named_selects(self) -> t.List[str]:
2660        return [e.output_name for e in self.expressions if e.alias_or_name]
2661
2662    @property
2663    def is_star(self) -> bool:
2664        return any(expression.is_star for expression in self.expressions)
2665
2666    @property
2667    def selects(self) -> t.List[Expression]:
2668        return self.expressions
2669
2670
2671class Subquery(DerivedTable, Unionable):
2672    arg_types = {
2673        "this": True,
2674        "alias": False,
2675        "with": False,
2676        **QUERY_MODIFIERS,
2677    }
2678
2679    def unnest(self):
2680        """
2681        Returns the first non subquery.
2682        """
2683        expression = self
2684        while isinstance(expression, Subquery):
2685            expression = expression.this
2686        return expression
2687
2688    @property
2689    def is_star(self) -> bool:
2690        return self.this.is_star
2691
2692    @property
2693    def output_name(self):
2694        return self.alias
2695
2696
2697class TableSample(Expression):
2698    arg_types = {
2699        "this": False,
2700        "method": False,
2701        "bucket_numerator": False,
2702        "bucket_denominator": False,
2703        "bucket_field": False,
2704        "percent": False,
2705        "rows": False,
2706        "size": False,
2707        "seed": False,
2708        "kind": False,
2709    }
2710
2711
2712class Tag(Expression):
2713    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2714
2715    arg_types = {
2716        "this": False,
2717        "prefix": False,
2718        "postfix": False,
2719    }
2720
2721
2722class Pivot(Expression):
2723    arg_types = {
2724        "this": False,
2725        "alias": False,
2726        "expressions": True,
2727        "field": True,
2728        "unpivot": True,
2729    }
2730
2731
2732class Window(Expression):
2733    arg_types = {
2734        "this": True,
2735        "partition_by": False,
2736        "order": False,
2737        "spec": False,
2738        "alias": False,
2739    }
2740
2741
2742class WindowSpec(Expression):
2743    arg_types = {
2744        "kind": False,
2745        "start": False,
2746        "start_side": False,
2747        "end": False,
2748        "end_side": False,
2749    }
2750
2751
2752class Where(Expression):
2753    pass
2754
2755
2756class Star(Expression):
2757    arg_types = {"except": False, "replace": False}
2758
2759    @property
2760    def name(self) -> str:
2761        return "*"
2762
2763    @property
2764    def output_name(self):
2765        return self.name
2766
2767
2768class Parameter(Expression):
2769    arg_types = {"this": True, "wrapped": False}
2770
2771
2772class SessionParameter(Expression):
2773    arg_types = {"this": True, "kind": False}
2774
2775
2776class Placeholder(Expression):
2777    arg_types = {"this": False}
2778
2779
2780class Null(Condition):
2781    arg_types: t.Dict[str, t.Any] = {}
2782
2783    @property
2784    def name(self) -> str:
2785        return "NULL"
2786
2787
2788class Boolean(Condition):
2789    pass
2790
2791
2792class DataType(Expression):
2793    arg_types = {
2794        "this": True,
2795        "expressions": False,
2796        "nested": False,
2797        "values": False,
2798        "prefix": False,
2799    }
2800
2801    class Type(AutoName):
2802        CHAR = auto()
2803        NCHAR = auto()
2804        VARCHAR = auto()
2805        NVARCHAR = auto()
2806        TEXT = auto()
2807        MEDIUMTEXT = auto()
2808        LONGTEXT = auto()
2809        MEDIUMBLOB = auto()
2810        LONGBLOB = auto()
2811        BINARY = auto()
2812        VARBINARY = auto()
2813        INT = auto()
2814        UINT = auto()
2815        TINYINT = auto()
2816        UTINYINT = auto()
2817        SMALLINT = auto()
2818        USMALLINT = auto()
2819        BIGINT = auto()
2820        UBIGINT = auto()
2821        FLOAT = auto()
2822        DOUBLE = auto()
2823        DECIMAL = auto()
2824        BIT = auto()
2825        BOOLEAN = auto()
2826        JSON = auto()
2827        JSONB = auto()
2828        INTERVAL = auto()
2829        TIME = auto()
2830        TIMESTAMP = auto()
2831        TIMESTAMPTZ = auto()
2832        TIMESTAMPLTZ = auto()
2833        DATE = auto()
2834        DATETIME = auto()
2835        ARRAY = auto()
2836        MAP = auto()
2837        UUID = auto()
2838        GEOGRAPHY = auto()
2839        GEOMETRY = auto()
2840        STRUCT = auto()
2841        NULLABLE = auto()
2842        HLLSKETCH = auto()
2843        HSTORE = auto()
2844        SUPER = auto()
2845        SERIAL = auto()
2846        SMALLSERIAL = auto()
2847        BIGSERIAL = auto()
2848        XML = auto()
2849        UNIQUEIDENTIFIER = auto()
2850        MONEY = auto()
2851        SMALLMONEY = auto()
2852        ROWVERSION = auto()
2853        IMAGE = auto()
2854        VARIANT = auto()
2855        OBJECT = auto()
2856        INET = auto()
2857        NULL = auto()
2858        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2859
2860    TEXT_TYPES = {
2861        Type.CHAR,
2862        Type.NCHAR,
2863        Type.VARCHAR,
2864        Type.NVARCHAR,
2865        Type.TEXT,
2866    }
2867
2868    INTEGER_TYPES = {
2869        Type.INT,
2870        Type.TINYINT,
2871        Type.SMALLINT,
2872        Type.BIGINT,
2873    }
2874
2875    FLOAT_TYPES = {
2876        Type.FLOAT,
2877        Type.DOUBLE,
2878    }
2879
2880    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2881
2882    TEMPORAL_TYPES = {
2883        Type.TIMESTAMP,
2884        Type.TIMESTAMPTZ,
2885        Type.TIMESTAMPLTZ,
2886        Type.DATE,
2887        Type.DATETIME,
2888    }
2889
2890    @classmethod
2891    def build(
2892        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2893    ) -> DataType:
2894        from sqlglot import parse_one
2895
2896        if isinstance(dtype, str):
2897            if dtype.upper() in cls.Type.__members__:
2898                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2899            else:
2900                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2901            if data_type_exp is None:
2902                raise ValueError(f"Unparsable data type value: {dtype}")
2903        elif isinstance(dtype, DataType.Type):
2904            data_type_exp = DataType(this=dtype)
2905        elif isinstance(dtype, DataType):
2906            return dtype
2907        else:
2908            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2909        return DataType(**{**data_type_exp.args, **kwargs})
2910
2911    def is_type(self, dtype: DataType.Type) -> bool:
2912        return self.this == dtype
2913
2914
2915# https://www.postgresql.org/docs/15/datatype-pseudo.html
2916class PseudoType(Expression):
2917    pass
2918
2919
2920class StructKwarg(Expression):
2921    arg_types = {"this": True, "expression": True}
2922
2923
2924# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
2925class SubqueryPredicate(Predicate):
2926    pass
2927
2928
2929class All(SubqueryPredicate):
2930    pass
2931
2932
2933class Any(SubqueryPredicate):
2934    pass
2935
2936
2937class Exists(SubqueryPredicate):
2938    pass
2939
2940
2941# Commands to interact with the databases or engines. For most of the command
2942# expressions we parse whatever comes after the command's name as a string.
2943class Command(Expression):
2944    arg_types = {"this": True, "expression": False}
2945
2946
2947class Transaction(Expression):
2948    arg_types = {"this": False, "modes": False}
2949
2950
2951class Commit(Expression):
2952    arg_types = {"chain": False}
2953
2954
2955class Rollback(Expression):
2956    arg_types = {"savepoint": False}
2957
2958
2959class AlterTable(Expression):
2960    arg_types = {"this": True, "actions": True, "exists": False}
2961
2962
2963class AddConstraint(Expression):
2964    arg_types = {"this": False, "expression": False, "enforced": False}
2965
2966
2967class DropPartition(Expression):
2968    arg_types = {"expressions": True, "exists": False}
2969
2970
2971# Binary expressions like (ADD a b)
2972class Binary(Expression):
2973    arg_types = {"this": True, "expression": True}
2974
2975    @property
2976    def left(self):
2977        return self.this
2978
2979    @property
2980    def right(self):
2981        return self.expression
2982
2983
2984class Add(Binary):
2985    pass
2986
2987
2988class Connector(Binary, Condition):
2989    pass
2990
2991
2992class And(Connector):
2993    pass
2994
2995
2996class Or(Connector):
2997    pass
2998
2999
3000class BitwiseAnd(Binary):
3001    pass
3002
3003
3004class BitwiseLeftShift(Binary):
3005    pass
3006
3007
3008class BitwiseOr(Binary):
3009    pass
3010
3011
3012class BitwiseRightShift(Binary):
3013    pass
3014
3015
3016class BitwiseXor(Binary):
3017    pass
3018
3019
3020class Div(Binary):
3021    pass
3022
3023
3024class Overlaps(Binary):
3025    pass
3026
3027
3028class Dot(Binary):
3029    @property
3030    def name(self) -> str:
3031        return self.expression.name
3032
3033    @classmethod
3034    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3035        """Build a Dot object with a sequence of expressions."""
3036        if len(expressions) < 2:
3037            raise ValueError(f"Dot requires >= 2 expressions.")
3038
3039        a, b, *expressions = expressions
3040        dot = Dot(this=a, expression=b)
3041
3042        for expression in expressions:
3043            dot = Dot(this=dot, expression=expression)
3044
3045        return dot
3046
3047
3048class DPipe(Binary):
3049    pass
3050
3051
3052class EQ(Binary, Predicate):
3053    pass
3054
3055
3056class NullSafeEQ(Binary, Predicate):
3057    pass
3058
3059
3060class NullSafeNEQ(Binary, Predicate):
3061    pass
3062
3063
3064class Distance(Binary):
3065    pass
3066
3067
3068class Escape(Binary):
3069    pass
3070
3071
3072class Glob(Binary, Predicate):
3073    pass
3074
3075
3076class GT(Binary, Predicate):
3077    pass
3078
3079
3080class GTE(Binary, Predicate):
3081    pass
3082
3083
3084class ILike(Binary, Predicate):
3085    pass
3086
3087
3088class ILikeAny(Binary, Predicate):
3089    pass
3090
3091
3092class IntDiv(Binary):
3093    pass
3094
3095
3096class Is(Binary, Predicate):
3097    pass
3098
3099
3100class Kwarg(Binary):
3101    """Kwarg in special functions like func(kwarg => y)."""
3102
3103
3104class Like(Binary, Predicate):
3105    pass
3106
3107
3108class LikeAny(Binary, Predicate):
3109    pass
3110
3111
3112class LT(Binary, Predicate):
3113    pass
3114
3115
3116class LTE(Binary, Predicate):
3117    pass
3118
3119
3120class Mod(Binary):
3121    pass
3122
3123
3124class Mul(Binary):
3125    pass
3126
3127
3128class NEQ(Binary, Predicate):
3129    pass
3130
3131
3132class SimilarTo(Binary, Predicate):
3133    pass
3134
3135
3136class Slice(Binary):
3137    arg_types = {"this": False, "expression": False}
3138
3139
3140class Sub(Binary):
3141    pass
3142
3143
3144class ArrayOverlaps(Binary):
3145    pass
3146
3147
3148# Unary Expressions
3149# (NOT a)
3150class Unary(Expression):
3151    pass
3152
3153
3154class BitwiseNot(Unary):
3155    pass
3156
3157
3158class Not(Unary, Condition):
3159    pass
3160
3161
3162class Paren(Unary, Condition):
3163    arg_types = {"this": True, "with": False}
3164
3165
3166class Neg(Unary):
3167    pass
3168
3169
3170# Special Functions
3171class Alias(Expression):
3172    arg_types = {"this": True, "alias": False}
3173
3174    @property
3175    def output_name(self):
3176        return self.alias
3177
3178
3179class Aliases(Expression):
3180    arg_types = {"this": True, "expressions": True}
3181
3182    @property
3183    def aliases(self):
3184        return self.expressions
3185
3186
3187class AtTimeZone(Expression):
3188    arg_types = {"this": True, "zone": True}
3189
3190
3191class Between(Predicate):
3192    arg_types = {"this": True, "low": True, "high": True}
3193
3194
3195class Bracket(Condition):
3196    arg_types = {"this": True, "expressions": True}
3197
3198
3199class Distinct(Expression):
3200    arg_types = {"expressions": False, "on": False}
3201
3202
3203class In(Predicate):
3204    arg_types = {
3205        "this": True,
3206        "expressions": False,
3207        "query": False,
3208        "unnest": False,
3209        "field": False,
3210        "is_global": False,
3211    }
3212
3213
3214class TimeUnit(Expression):
3215    """Automatically converts unit arg into a var."""
3216
3217    arg_types = {"unit": False}
3218
3219    def __init__(self, **args):
3220        unit = args.get("unit")
3221        if isinstance(unit, (Column, Literal)):
3222            args["unit"] = Var(this=unit.name)
3223        elif isinstance(unit, Week):
3224            unit.set("this", Var(this=unit.this.name))
3225        super().__init__(**args)
3226
3227
3228class Interval(TimeUnit):
3229    arg_types = {"this": False, "unit": False}
3230
3231
3232class IgnoreNulls(Expression):
3233    pass
3234
3235
3236class RespectNulls(Expression):
3237    pass
3238
3239
3240# Functions
3241class Func(Condition):
3242    """
3243    The base class for all function expressions.
3244
3245    Attributes:
3246        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3247            treated as a variable length argument and the argument's value will be stored as a list.
3248        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3249            for this function expression. These values are used to map this node to a name during parsing
3250            as well as to provide the function's name during SQL string generation. By default the SQL
3251            name is set to the expression's class name transformed to snake case.
3252    """
3253
3254    is_var_len_args = False
3255
3256    @classmethod
3257    def from_arg_list(cls, args):
3258        if cls.is_var_len_args:
3259            all_arg_keys = list(cls.arg_types)
3260            # If this function supports variable length argument treat the last argument as such.
3261            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3262            num_non_var = len(non_var_len_arg_keys)
3263
3264            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3265            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3266        else:
3267            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3268
3269        return cls(**args_dict)
3270
3271    @classmethod
3272    def sql_names(cls):
3273        if cls is Func:
3274            raise NotImplementedError(
3275                "SQL name is only supported by concrete function implementations"
3276            )
3277        if "_sql_names" not in cls.__dict__:
3278            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3279        return cls._sql_names
3280
3281    @classmethod
3282    def sql_name(cls):
3283        return cls.sql_names()[0]
3284
3285    @classmethod
3286    def default_parser_mappings(cls):
3287        return {name: cls.from_arg_list for name in cls.sql_names()}
3288
3289
3290class AggFunc(Func):
3291    pass
3292
3293
3294class Abs(Func):
3295    pass
3296
3297
3298class Anonymous(Func):
3299    arg_types = {"this": True, "expressions": False}
3300    is_var_len_args = True
3301
3302
3303# https://docs.snowflake.com/en/sql-reference/functions/hll
3304# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3305class Hll(AggFunc):
3306    arg_types = {"this": True, "expressions": False}
3307    is_var_len_args = True
3308
3309
3310class ApproxDistinct(AggFunc):
3311    arg_types = {"this": True, "accuracy": False}
3312
3313
3314class Array(Func):
3315    arg_types = {"expressions": False}
3316    is_var_len_args = True
3317
3318
3319# https://docs.snowflake.com/en/sql-reference/functions/to_char
3320class ToChar(Func):
3321    arg_types = {"this": True, "format": False}
3322
3323
3324class GenerateSeries(Func):
3325    arg_types = {"start": True, "end": True, "step": False}
3326
3327
3328class ArrayAgg(AggFunc):
3329    pass
3330
3331
3332class ArrayAll(Func):
3333    arg_types = {"this": True, "expression": True}
3334
3335
3336class ArrayAny(Func):
3337    arg_types = {"this": True, "expression": True}
3338
3339
3340class ArrayConcat(Func):
3341    arg_types = {"this": True, "expressions": False}
3342    is_var_len_args = True
3343
3344
3345class ArrayContains(Binary, Func):
3346    pass
3347
3348
3349class ArrayContained(Binary):
3350    pass
3351
3352
3353class ArrayFilter(Func):
3354    arg_types = {"this": True, "expression": True}
3355    _sql_names = ["FILTER", "ARRAY_FILTER"]
3356
3357
3358class ArrayJoin(Func):
3359    arg_types = {"this": True, "expression": True, "null": False}
3360
3361
3362class ArraySize(Func):
3363    arg_types = {"this": True, "expression": False}
3364
3365
3366class ArraySort(Func):
3367    arg_types = {"this": True, "expression": False}
3368
3369
3370class ArraySum(Func):
3371    pass
3372
3373
3374class ArrayUnionAgg(AggFunc):
3375    pass
3376
3377
3378class Avg(AggFunc):
3379    pass
3380
3381
3382class AnyValue(AggFunc):
3383    pass
3384
3385
3386class Case(Func):
3387    arg_types = {"this": False, "ifs": True, "default": False}
3388
3389
3390class Cast(Func):
3391    arg_types = {"this": True, "to": True}
3392
3393    @property
3394    def name(self) -> str:
3395        return self.this.name
3396
3397    @property
3398    def to(self):
3399        return self.args["to"]
3400
3401    @property
3402    def output_name(self):
3403        return self.name
3404
3405    def is_type(self, dtype: DataType.Type) -> bool:
3406        return self.to.is_type(dtype)
3407
3408
3409class Collate(Binary):
3410    pass
3411
3412
3413class TryCast(Cast):
3414    pass
3415
3416
3417class Ceil(Func):
3418    arg_types = {"this": True, "decimals": False}
3419    _sql_names = ["CEIL", "CEILING"]
3420
3421
3422class Coalesce(Func):
3423    arg_types = {"this": True, "expressions": False}
3424    is_var_len_args = True
3425
3426
3427class Concat(Func):
3428    arg_types = {"expressions": True}
3429    is_var_len_args = True
3430
3431
3432class ConcatWs(Concat):
3433    _sql_names = ["CONCAT_WS"]
3434
3435
3436class Count(AggFunc):
3437    arg_types = {"this": False}
3438
3439
3440class CountIf(AggFunc):
3441    pass
3442
3443
3444class CurrentDate(Func):
3445    arg_types = {"this": False}
3446
3447
3448class CurrentDatetime(Func):
3449    arg_types = {"this": False}
3450
3451
3452class CurrentTime(Func):
3453    arg_types = {"this": False}
3454
3455
3456class CurrentTimestamp(Func):
3457    arg_types = {"this": False}
3458
3459
3460class CurrentUser(Func):
3461    arg_types = {"this": False}
3462
3463
3464class DateAdd(Func, TimeUnit):
3465    arg_types = {"this": True, "expression": True, "unit": False}
3466
3467
3468class DateSub(Func, TimeUnit):
3469    arg_types = {"this": True, "expression": True, "unit": False}
3470
3471
3472class DateDiff(Func, TimeUnit):
3473    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3474    arg_types = {"this": True, "expression": True, "unit": False}
3475
3476
3477class DateTrunc(Func):
3478    arg_types = {"unit": True, "this": True, "zone": False}
3479
3480
3481class DatetimeAdd(Func, TimeUnit):
3482    arg_types = {"this": True, "expression": True, "unit": False}
3483
3484
3485class DatetimeSub(Func, TimeUnit):
3486    arg_types = {"this": True, "expression": True, "unit": False}
3487
3488
3489class DatetimeDiff(Func, TimeUnit):
3490    arg_types = {"this": True, "expression": True, "unit": False}
3491
3492
3493class DatetimeTrunc(Func, TimeUnit):
3494    arg_types = {"this": True, "unit": True, "zone": False}
3495
3496
3497class DayOfWeek(Func):
3498    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
3499
3500
3501class DayOfMonth(Func):
3502    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
3503
3504
3505class DayOfYear(Func):
3506    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
3507
3508
3509class WeekOfYear(Func):
3510    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
3511
3512
3513class LastDateOfMonth(Func):
3514    pass
3515
3516
3517class Extract(Func):
3518    arg_types = {"this": True, "expression": True}
3519
3520
3521class TimestampAdd(Func, TimeUnit):
3522    arg_types = {"this": True, "expression": True, "unit": False}
3523
3524
3525class TimestampSub(Func, TimeUnit):
3526    arg_types = {"this": True, "expression": True, "unit": False}
3527
3528
3529class TimestampDiff(Func, TimeUnit):
3530    arg_types = {"this": True, "expression": True, "unit": False}
3531
3532
3533class TimestampTrunc(Func, TimeUnit):
3534    arg_types = {"this": True, "unit": True, "zone": False}
3535
3536
3537class TimeAdd(Func, TimeUnit):
3538    arg_types = {"this": True, "expression": True, "unit": False}
3539
3540
3541class TimeSub(Func, TimeUnit):
3542    arg_types = {"this": True, "expression": True, "unit": False}
3543
3544
3545class TimeDiff(Func, TimeUnit):
3546    arg_types = {"this": True, "expression": True, "unit": False}
3547
3548
3549class TimeTrunc(Func, TimeUnit):
3550    arg_types = {"this": True, "unit": True, "zone": False}
3551
3552
3553class DateFromParts(Func):
3554    _sql_names = ["DATEFROMPARTS"]
3555    arg_types = {"year": True, "month": True, "day": True}
3556
3557
3558class DateStrToDate(Func):
3559    pass
3560
3561
3562class DateToDateStr(Func):
3563    pass
3564
3565
3566class DateToDi(Func):
3567    pass
3568
3569
3570class Day(Func):
3571    pass
3572
3573
3574class Decode(Func):
3575    arg_types = {"this": True, "charset": True, "replace": False}
3576
3577
3578class DiToDate(Func):
3579    pass
3580
3581
3582class Encode(Func):
3583    arg_types = {"this": True, "charset": True}
3584
3585
3586class Exp(Func):
3587    pass
3588
3589
3590class Explode(Func):
3591    pass
3592
3593
3594class ExponentialTimeDecayedAvg(AggFunc):
3595    arg_types = {"this": True, "time": False, "decay": False}
3596
3597
3598class Floor(Func):
3599    arg_types = {"this": True, "decimals": False}
3600
3601
3602class Greatest(Func):
3603    arg_types = {"this": True, "expressions": False}
3604    is_var_len_args = True
3605
3606
3607class GroupConcat(Func):
3608    arg_types = {"this": True, "separator": False}
3609
3610
3611class GroupUniqArray(AggFunc):
3612    arg_types = {"this": True, "size": False}
3613
3614
3615class Hex(Func):
3616    pass
3617
3618
3619class Histogram(AggFunc):
3620    arg_types = {"this": True, "bins": False}
3621
3622
3623class If(Func):
3624    arg_types = {"this": True, "true": True, "false": False}
3625
3626
3627class IfNull(Func):
3628    arg_types = {"this": True, "expression": False}
3629    _sql_names = ["IFNULL", "NVL"]
3630
3631
3632class Initcap(Func):
3633    pass
3634
3635
3636class JSONKeyValue(Expression):
3637    arg_types = {"this": True, "expression": True}
3638
3639
3640class JSONObject(Func):
3641    arg_types = {
3642        "expressions": False,
3643        "null_handling": False,
3644        "unique_keys": False,
3645        "return_type": False,
3646        "format_json": False,
3647        "encoding": False,
3648    }
3649
3650
3651class JSONBContains(Binary):
3652    _sql_names = ["JSONB_CONTAINS"]
3653
3654
3655class JSONExtract(Binary, Func):
3656    _sql_names = ["JSON_EXTRACT"]
3657
3658
3659class JSONExtractScalar(JSONExtract):
3660    _sql_names = ["JSON_EXTRACT_SCALAR"]
3661
3662
3663class JSONBExtract(JSONExtract):
3664    _sql_names = ["JSONB_EXTRACT"]
3665
3666
3667class JSONBExtractScalar(JSONExtract):
3668    _sql_names = ["JSONB_EXTRACT_SCALAR"]
3669
3670
3671class JSONFormat(Func):
3672    arg_types = {"this": False, "options": False}
3673    _sql_names = ["JSON_FORMAT"]
3674
3675
3676class Least(Func):
3677    arg_types = {"expressions": False}
3678    is_var_len_args = True
3679
3680
3681class Length(Func):
3682    pass
3683
3684
3685class Levenshtein(Func):
3686    arg_types = {
3687        "this": True,
3688        "expression": False,
3689        "ins_cost": False,
3690        "del_cost": False,
3691        "sub_cost": False,
3692    }
3693
3694
3695class Ln(Func):
3696    pass
3697
3698
3699class Log(Func):
3700    arg_types = {"this": True, "expression": False}
3701
3702
3703class Log2(Func):
3704    pass
3705
3706
3707class Log10(Func):
3708    pass
3709
3710
3711class LogicalOr(AggFunc):
3712    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
3713
3714
3715class LogicalAnd(AggFunc):
3716    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
3717
3718
3719class Lower(Func):
3720    _sql_names = ["LOWER", "LCASE"]
3721
3722
3723class Map(Func):
3724    arg_types = {"keys": False, "values": False}
3725
3726
3727class VarMap(Func):
3728    arg_types = {"keys": True, "values": True}
3729    is_var_len_args = True
3730
3731
3732# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
3733class MatchAgainst(Func):
3734    arg_types = {"this": True, "expressions": True, "modifier": False}
3735
3736
3737class Max(AggFunc):
3738    arg_types = {"this": True, "expressions": False}
3739    is_var_len_args = True
3740
3741
3742class Min(AggFunc):
3743    arg_types = {"this": True, "expressions": False}
3744    is_var_len_args = True
3745
3746
3747class Month(Func):
3748    pass
3749
3750
3751class Nvl2(Func):
3752    arg_types = {"this": True, "true": True, "false": False}
3753
3754
3755class Posexplode(Func):
3756    pass
3757
3758
3759class Pow(Binary, Func):
3760    _sql_names = ["POWER", "POW"]
3761
3762
3763class PercentileCont(AggFunc):
3764    pass
3765
3766
3767class PercentileDisc(AggFunc):
3768    pass
3769
3770
3771class Quantile(AggFunc):
3772    arg_types = {"this": True, "quantile": True}
3773
3774
3775# Clickhouse-specific:
3776# https://clickhouse.com/docs/en/sql-reference/aggregate-functions/reference/quantiles/#quantiles
3777class Quantiles(AggFunc):
3778    arg_types = {"parameters": True, "expressions": True}
3779    is_var_len_args = True
3780
3781
3782class QuantileIf(AggFunc):
3783    arg_types = {"parameters": True, "expressions": True}
3784
3785
3786class ApproxQuantile(Quantile):
3787    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
3788
3789
3790class RangeN(Func):
3791    arg_types = {"this": True, "expressions": True, "each": False}
3792
3793
3794class ReadCSV(Func):
3795    _sql_names = ["READ_CSV"]
3796    is_var_len_args = True
3797    arg_types = {"this": True, "expressions": False}
3798
3799
3800class Reduce(Func):
3801    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
3802
3803
3804class RegexpExtract(Func):
3805    arg_types = {
3806        "this": True,
3807        "expression": True,
3808        "position": False,
3809        "occurrence": False,
3810        "group": False,
3811    }
3812
3813
3814class RegexpLike(Func):
3815    arg_types = {"this": True, "expression": True, "flag": False}
3816
3817
3818class RegexpILike(Func):
3819    arg_types = {"this": True, "expression": True, "flag": False}
3820
3821
3822# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
3823# limit is the number of times a pattern is applied
3824class RegexpSplit(Func):
3825    arg_types = {"this": True, "expression": True, "limit": False}
3826
3827
3828class Repeat(Func):
3829    arg_types = {"this": True, "times": True}
3830
3831
3832class Round(Func):
3833    arg_types = {"this": True, "decimals": False}
3834
3835
3836class RowNumber(Func):
3837    arg_types: t.Dict[str, t.Any] = {}
3838
3839
3840class SafeDivide(Func):
3841    arg_types = {"this": True, "expression": True}
3842
3843
3844class SetAgg(AggFunc):
3845    pass
3846
3847
3848class SortArray(Func):
3849    arg_types = {"this": True, "asc": False}
3850
3851
3852class Split(Func):
3853    arg_types = {"this": True, "expression": True, "limit": False}
3854
3855
3856# Start may be omitted in the case of postgres
3857# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
3858class Substring(Func):
3859    arg_types = {"this": True, "start": False, "length": False}
3860
3861
3862class StrPosition(Func):
3863    arg_types = {
3864        "this": True,
3865        "substr": True,
3866        "position": False,
3867        "instance": False,
3868    }
3869
3870
3871class StrToDate(Func):
3872    arg_types = {"this": True, "format": True}
3873
3874
3875class StrToTime(Func):
3876    arg_types = {"this": True, "format": True}
3877
3878
3879# Spark allows unix_timestamp()
3880# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
3881class StrToUnix(Func):
3882    arg_types = {"this": False, "format": False}
3883
3884
3885class NumberToStr(Func):
3886    arg_types = {"this": True, "format": True}
3887
3888
3889class Struct(Func):
3890    arg_types = {"expressions": True}
3891    is_var_len_args = True
3892
3893
3894class StructExtract(Func):
3895    arg_types = {"this": True, "expression": True}
3896
3897
3898class Sum(AggFunc):
3899    pass
3900
3901
3902class Sqrt(Func):
3903    pass
3904
3905
3906class Stddev(AggFunc):
3907    pass
3908
3909
3910class StddevPop(AggFunc):
3911    pass
3912
3913
3914class StddevSamp(AggFunc):
3915    pass
3916
3917
3918class TimeToStr(Func):
3919    arg_types = {"this": True, "format": True}
3920
3921
3922class TimeToTimeStr(Func):
3923    pass
3924
3925
3926class TimeToUnix(Func):
3927    pass
3928
3929
3930class TimeStrToDate(Func):
3931    pass
3932
3933
3934class TimeStrToTime(Func):
3935    pass
3936
3937
3938class TimeStrToUnix(Func):
3939    pass
3940
3941
3942class Trim(Func):
3943    arg_types = {
3944        "this": True,
3945        "expression": False,
3946        "position": False,
3947        "collation": False,
3948    }
3949
3950
3951class TsOrDsAdd(Func, TimeUnit):
3952    arg_types = {"this": True, "expression": True, "unit": False}
3953
3954
3955class TsOrDsToDateStr(Func):
3956    pass
3957
3958
3959class TsOrDsToDate(Func):
3960    arg_types = {"this": True, "format": False}
3961
3962
3963class TsOrDiToDi(Func):
3964    pass
3965
3966
3967class Unhex(Func):
3968    pass
3969
3970
3971class UnixToStr(Func):
3972    arg_types = {"this": True, "format": False}
3973
3974
3975# https://prestodb.io/docs/current/functions/datetime.html
3976# presto has weird zone/hours/minutes
3977class UnixToTime(Func):
3978    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3979
3980    SECONDS = Literal.string("seconds")
3981    MILLIS = Literal.string("millis")
3982    MICROS = Literal.string("micros")
3983
3984
3985class UnixToTimeStr(Func):
3986    pass
3987
3988
3989class Upper(Func):
3990    _sql_names = ["UPPER", "UCASE"]
3991
3992
3993class Variance(AggFunc):
3994    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
3995
3996
3997class VariancePop(AggFunc):
3998    _sql_names = ["VARIANCE_POP", "VAR_POP"]
3999
4000
4001class Week(Func):
4002    arg_types = {"this": True, "mode": False}
4003
4004
4005class XMLTable(Func):
4006    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4007
4008
4009class Year(Func):
4010    pass
4011
4012
4013class Use(Expression):
4014    arg_types = {"this": True, "kind": False}
4015
4016
4017class Merge(Expression):
4018    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4019
4020
4021class When(Func):
4022    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4023
4024
4025def _norm_arg(arg):
4026    return arg.lower() if type(arg) is str else arg
4027
4028
4029ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4030
4031
4032# Helpers
4033def maybe_parse(
4034    sql_or_expression: ExpOrStr,
4035    *,
4036    into: t.Optional[IntoType] = None,
4037    dialect: DialectType = None,
4038    prefix: t.Optional[str] = None,
4039    copy: bool = False,
4040    **opts,
4041) -> Expression:
4042    """Gracefully handle a possible string or expression.
4043
4044    Example:
4045        >>> maybe_parse("1")
4046        (LITERAL this: 1, is_string: False)
4047        >>> maybe_parse(to_identifier("x"))
4048        (IDENTIFIER this: x, quoted: False)
4049
4050    Args:
4051        sql_or_expression: the SQL code string or an expression
4052        into: the SQLGlot Expression to parse into
4053        dialect: the dialect used to parse the input expressions (in the case that an
4054            input expression is a SQL string).
4055        prefix: a string to prefix the sql with before it gets parsed
4056            (automatically includes a space)
4057        copy: whether or not to copy the expression.
4058        **opts: other options to use to parse the input expressions (again, in the case
4059            that an input expression is a SQL string).
4060
4061    Returns:
4062        Expression: the parsed or given expression.
4063    """
4064    if isinstance(sql_or_expression, Expression):
4065        if copy:
4066            return sql_or_expression.copy()
4067        return sql_or_expression
4068
4069    import sqlglot
4070
4071    sql = str(sql_or_expression)
4072    if prefix:
4073        sql = f"{prefix} {sql}"
4074    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4075
4076
4077def _maybe_copy(instance, copy=True):
4078    return instance.copy() if copy else instance
4079
4080
4081def _is_wrong_expression(expression, into):
4082    return isinstance(expression, Expression) and not isinstance(expression, into)
4083
4084
4085def _apply_builder(
4086    expression,
4087    instance,
4088    arg,
4089    copy=True,
4090    prefix=None,
4091    into=None,
4092    dialect=None,
4093    **opts,
4094):
4095    if _is_wrong_expression(expression, into):
4096        expression = into(this=expression)
4097    instance = _maybe_copy(instance, copy)
4098    expression = maybe_parse(
4099        sql_or_expression=expression,
4100        prefix=prefix,
4101        into=into,
4102        dialect=dialect,
4103        **opts,
4104    )
4105    instance.set(arg, expression)
4106    return instance
4107
4108
4109def _apply_child_list_builder(
4110    *expressions,
4111    instance,
4112    arg,
4113    append=True,
4114    copy=True,
4115    prefix=None,
4116    into=None,
4117    dialect=None,
4118    properties=None,
4119    **opts,
4120):
4121    instance = _maybe_copy(instance, copy)
4122    parsed = []
4123    for expression in expressions:
4124        if _is_wrong_expression(expression, into):
4125            expression = into(expressions=[expression])
4126        expression = maybe_parse(
4127            expression,
4128            into=into,
4129            dialect=dialect,
4130            prefix=prefix,
4131            **opts,
4132        )
4133        parsed.extend(expression.expressions)
4134
4135    existing = instance.args.get(arg)
4136    if append and existing:
4137        parsed = existing.expressions + parsed
4138
4139    child = into(expressions=parsed)
4140    for k, v in (properties or {}).items():
4141        child.set(k, v)
4142    instance.set(arg, child)
4143    return instance
4144
4145
4146def _apply_list_builder(
4147    *expressions,
4148    instance,
4149    arg,
4150    append=True,
4151    copy=True,
4152    prefix=None,
4153    into=None,
4154    dialect=None,
4155    **opts,
4156):
4157    inst = _maybe_copy(instance, copy)
4158
4159    expressions = [
4160        maybe_parse(
4161            sql_or_expression=expression,
4162            into=into,
4163            prefix=prefix,
4164            dialect=dialect,
4165            **opts,
4166        )
4167        for expression in expressions
4168    ]
4169
4170    existing_expressions = inst.args.get(arg)
4171    if append and existing_expressions:
4172        expressions = existing_expressions + expressions
4173
4174    inst.set(arg, expressions)
4175    return inst
4176
4177
4178def _apply_conjunction_builder(
4179    *expressions,
4180    instance,
4181    arg,
4182    into=None,
4183    append=True,
4184    copy=True,
4185    dialect=None,
4186    **opts,
4187):
4188    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4189    if not expressions:
4190        return instance
4191
4192    inst = _maybe_copy(instance, copy)
4193
4194    existing = inst.args.get(arg)
4195    if append and existing is not None:
4196        expressions = [existing.this if into else existing] + list(expressions)
4197
4198    node = and_(*expressions, dialect=dialect, **opts)
4199
4200    inst.set(arg, into(this=node) if into else node)
4201    return inst
4202
4203
4204def _combine(expressions, operator, dialect=None, **opts):
4205    expressions = [condition(expression, dialect=dialect, **opts) for expression in expressions]
4206    this = expressions[0]
4207    if expressions[1:]:
4208        this = _wrap_operator(this)
4209    for expression in expressions[1:]:
4210        this = operator(this=this, expression=_wrap_operator(expression))
4211    return this
4212
4213
4214def _wrap_operator(expression):
4215    if isinstance(expression, (And, Or, Not)):
4216        expression = Paren(this=expression)
4217    return expression
4218
4219
4220def union(left, right, distinct=True, dialect=None, **opts):
4221    """
4222    Initializes a syntax tree from one UNION expression.
4223
4224    Example:
4225        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4226        'SELECT * FROM foo UNION SELECT * FROM bla'
4227
4228    Args:
4229        left (str | Expression): the SQL code string corresponding to the left-hand side.
4230            If an `Expression` instance is passed, it will be used as-is.
4231        right (str | Expression): the SQL code string corresponding to the right-hand side.
4232            If an `Expression` instance is passed, it will be used as-is.
4233        distinct (bool): set the DISTINCT flag if and only if this is true.
4234        dialect (str): the dialect used to parse the input expression.
4235        opts (kwargs): other options to use to parse the input expressions.
4236    Returns:
4237        Union: the syntax tree for the UNION expression.
4238    """
4239    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4240    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4241
4242    return Union(this=left, expression=right, distinct=distinct)
4243
4244
4245def intersect(left, right, distinct=True, dialect=None, **opts):
4246    """
4247    Initializes a syntax tree from one INTERSECT expression.
4248
4249    Example:
4250        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4251        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4252
4253    Args:
4254        left (str | Expression): the SQL code string corresponding to the left-hand side.
4255            If an `Expression` instance is passed, it will be used as-is.
4256        right (str | Expression): the SQL code string corresponding to the right-hand side.
4257            If an `Expression` instance is passed, it will be used as-is.
4258        distinct (bool): set the DISTINCT flag if and only if this is true.
4259        dialect (str): the dialect used to parse the input expression.
4260        opts (kwargs): other options to use to parse the input expressions.
4261    Returns:
4262        Intersect: the syntax tree for the INTERSECT expression.
4263    """
4264    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4265    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4266
4267    return Intersect(this=left, expression=right, distinct=distinct)
4268
4269
4270def except_(left, right, distinct=True, dialect=None, **opts):
4271    """
4272    Initializes a syntax tree from one EXCEPT expression.
4273
4274    Example:
4275        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4276        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4277
4278    Args:
4279        left (str | Expression): the SQL code string corresponding to the left-hand side.
4280            If an `Expression` instance is passed, it will be used as-is.
4281        right (str | Expression): the SQL code string corresponding to the right-hand side.
4282            If an `Expression` instance is passed, it will be used as-is.
4283        distinct (bool): set the DISTINCT flag if and only if this is true.
4284        dialect (str): the dialect used to parse the input expression.
4285        opts (kwargs): other options to use to parse the input expressions.
4286    Returns:
4287        Except: the syntax tree for the EXCEPT statement.
4288    """
4289    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4290    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4291
4292    return Except(this=left, expression=right, distinct=distinct)
4293
4294
4295def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4296    """
4297    Initializes a syntax tree from one or multiple SELECT expressions.
4298
4299    Example:
4300        >>> select("col1", "col2").from_("tbl").sql()
4301        'SELECT col1, col2 FROM tbl'
4302
4303    Args:
4304        *expressions: the SQL code string to parse as the expressions of a
4305            SELECT statement. If an Expression instance is passed, this is used as-is.
4306        dialect: the dialect used to parse the input expressions (in the case that an
4307            input expression is a SQL string).
4308        **opts: other options to use to parse the input expressions (again, in the case
4309            that an input expression is a SQL string).
4310
4311    Returns:
4312        Select: the syntax tree for the SELECT statement.
4313    """
4314    return Select().select(*expressions, dialect=dialect, **opts)
4315
4316
4317def from_(*expressions, dialect=None, **opts) -> Select:
4318    """
4319    Initializes a syntax tree from a FROM expression.
4320
4321    Example:
4322        >>> from_("tbl").select("col1", "col2").sql()
4323        'SELECT col1, col2 FROM tbl'
4324
4325    Args:
4326        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4327            SELECT statement. If an Expression instance is passed, this is used as-is.
4328        dialect (str): the dialect used to parse the input expression (in the case that the
4329            input expression is a SQL string).
4330        **opts: other options to use to parse the input expressions (again, in the case
4331            that the input expression is a SQL string).
4332
4333    Returns:
4334        Select: the syntax tree for the SELECT statement.
4335    """
4336    return Select().from_(*expressions, dialect=dialect, **opts)
4337
4338
4339def update(
4340    table: str | Table,
4341    properties: dict,
4342    where: t.Optional[ExpOrStr] = None,
4343    from_: t.Optional[ExpOrStr] = None,
4344    dialect: DialectType = None,
4345    **opts,
4346) -> Update:
4347    """
4348    Creates an update statement.
4349
4350    Example:
4351        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4352        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4353
4354    Args:
4355        *properties: dictionary of properties to set which are
4356            auto converted to sql objects eg None -> NULL
4357        where: sql conditional parsed into a WHERE statement
4358        from_: sql statement parsed into a FROM statement
4359        dialect: the dialect used to parse the input expressions.
4360        **opts: other options to use to parse the input expressions.
4361
4362    Returns:
4363        Update: the syntax tree for the UPDATE statement.
4364    """
4365    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4366    update_expr.set(
4367        "expressions",
4368        [
4369            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4370            for k, v in properties.items()
4371        ],
4372    )
4373    if from_:
4374        update_expr.set(
4375            "from",
4376            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4377        )
4378    if isinstance(where, Condition):
4379        where = Where(this=where)
4380    if where:
4381        update_expr.set(
4382            "where",
4383            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4384        )
4385    return update_expr
4386
4387
4388def delete(
4389    table: ExpOrStr,
4390    where: t.Optional[ExpOrStr] = None,
4391    returning: t.Optional[ExpOrStr] = None,
4392    dialect: DialectType = None,
4393    **opts,
4394) -> Delete:
4395    """
4396    Builds a delete statement.
4397
4398    Example:
4399        >>> delete("my_table", where="id > 1").sql()
4400        'DELETE FROM my_table WHERE id > 1'
4401
4402    Args:
4403        where: sql conditional parsed into a WHERE statement
4404        returning: sql conditional parsed into a RETURNING statement
4405        dialect: the dialect used to parse the input expressions.
4406        **opts: other options to use to parse the input expressions.
4407
4408    Returns:
4409        Delete: the syntax tree for the DELETE statement.
4410    """
4411    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4412    if where:
4413        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4414    if returning:
4415        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4416    return delete_expr
4417
4418
4419def condition(expression, dialect=None, **opts) -> Condition:
4420    """
4421    Initialize a logical condition expression.
4422
4423    Example:
4424        >>> condition("x=1").sql()
4425        'x = 1'
4426
4427        This is helpful for composing larger logical syntax trees:
4428        >>> where = condition("x=1")
4429        >>> where = where.and_("y=1")
4430        >>> Select().from_("tbl").select("*").where(where).sql()
4431        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4432
4433    Args:
4434        *expression (str | Expression): the SQL code string to parse.
4435            If an Expression instance is passed, this is used as-is.
4436        dialect (str): the dialect used to parse the input expression (in the case that the
4437            input expression is a SQL string).
4438        **opts: other options to use to parse the input expressions (again, in the case
4439            that the input expression is a SQL string).
4440
4441    Returns:
4442        Condition: the expression
4443    """
4444    return maybe_parse(  # type: ignore
4445        expression,
4446        into=Condition,
4447        dialect=dialect,
4448        **opts,
4449    )
4450
4451
4452def and_(*expressions, dialect=None, **opts) -> And:
4453    """
4454    Combine multiple conditions with an AND logical operator.
4455
4456    Example:
4457        >>> and_("x=1", and_("y=1", "z=1")).sql()
4458        'x = 1 AND (y = 1 AND z = 1)'
4459
4460    Args:
4461        *expressions (str | Expression): the SQL code strings to parse.
4462            If an Expression instance is passed, this is used as-is.
4463        dialect (str): the dialect used to parse the input expression.
4464        **opts: other options to use to parse the input expressions.
4465
4466    Returns:
4467        And: the new condition
4468    """
4469    return _combine(expressions, And, dialect, **opts)
4470
4471
4472def or_(*expressions, dialect=None, **opts) -> Or:
4473    """
4474    Combine multiple conditions with an OR logical operator.
4475
4476    Example:
4477        >>> or_("x=1", or_("y=1", "z=1")).sql()
4478        'x = 1 OR (y = 1 OR z = 1)'
4479
4480    Args:
4481        *expressions (str | Expression): the SQL code strings to parse.
4482            If an Expression instance is passed, this is used as-is.
4483        dialect (str): the dialect used to parse the input expression.
4484        **opts: other options to use to parse the input expressions.
4485
4486    Returns:
4487        Or: the new condition
4488    """
4489    return _combine(expressions, Or, dialect, **opts)
4490
4491
4492def not_(expression, dialect=None, **opts) -> Not:
4493    """
4494    Wrap a condition with a NOT operator.
4495
4496    Example:
4497        >>> not_("this_suit='black'").sql()
4498        "NOT this_suit = 'black'"
4499
4500    Args:
4501        expression (str | Expression): the SQL code strings to parse.
4502            If an Expression instance is passed, this is used as-is.
4503        dialect (str): the dialect used to parse the input expression.
4504        **opts: other options to use to parse the input expressions.
4505
4506    Returns:
4507        Not: the new condition
4508    """
4509    this = condition(
4510        expression,
4511        dialect=dialect,
4512        **opts,
4513    )
4514    return Not(this=_wrap_operator(this))
4515
4516
4517def paren(expression) -> Paren:
4518    return Paren(this=expression)
4519
4520
4521SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
4522
4523
4524@t.overload
4525def to_identifier(name: None, quoted: t.Optional[bool] = None) -> None:
4526    ...
4527
4528
4529@t.overload
4530def to_identifier(name: str | Identifier, quoted: t.Optional[bool] = None) -> Identifier:
4531    ...
4532
4533
4534def to_identifier(name, quoted=None):
4535    """Builds an identifier.
4536
4537    Args:
4538        name: The name to turn into an identifier.
4539        quoted: Whether or not force quote the identifier.
4540
4541    Returns:
4542        The identifier ast node.
4543    """
4544
4545    if name is None:
4546        return None
4547
4548    if isinstance(name, Identifier):
4549        identifier = name
4550    elif isinstance(name, str):
4551        identifier = Identifier(
4552            this=name,
4553            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4554        )
4555    else:
4556        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4557    return identifier
4558
4559
4560INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
4561
4562
4563def to_interval(interval: str | Literal) -> Interval:
4564    """Builds an interval expression from a string like '1 day' or '5 months'."""
4565    if isinstance(interval, Literal):
4566        if not interval.is_string:
4567            raise ValueError("Invalid interval string.")
4568
4569        interval = interval.this
4570
4571    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4572
4573    if not interval_parts:
4574        raise ValueError("Invalid interval string.")
4575
4576    return Interval(
4577        this=Literal.string(interval_parts.group(1)),
4578        unit=Var(this=interval_parts.group(2)),
4579    )
4580
4581
4582@t.overload
4583def to_table(sql_path: str | Table, **kwargs) -> Table:
4584    ...
4585
4586
4587@t.overload
4588def to_table(sql_path: None, **kwargs) -> None:
4589    ...
4590
4591
4592def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4593    """
4594    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4595    If a table is passed in then that table is returned.
4596
4597    Args:
4598        sql_path: a `[catalog].[schema].[table]` string.
4599
4600    Returns:
4601        A table expression.
4602    """
4603    if sql_path is None or isinstance(sql_path, Table):
4604        return sql_path
4605    if not isinstance(sql_path, str):
4606        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4607
4608    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4609    return Table(this=table_name, db=db, catalog=catalog, **kwargs)
4610
4611
4612def to_column(sql_path: str | Column, **kwargs) -> Column:
4613    """
4614    Create a column from a `[table].[column]` sql path. Schema is optional.
4615
4616    If a column is passed in then that column is returned.
4617
4618    Args:
4619        sql_path: `[table].[column]` string
4620    Returns:
4621        Table: A column expression
4622    """
4623    if sql_path is None or isinstance(sql_path, Column):
4624        return sql_path
4625    if not isinstance(sql_path, str):
4626        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4627    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
4628
4629
4630def alias_(
4631    expression: ExpOrStr,
4632    alias: str | Identifier,
4633    table: bool | t.Sequence[str | Identifier] = False,
4634    quoted: t.Optional[bool] = None,
4635    dialect: DialectType = None,
4636    **opts,
4637):
4638    """Create an Alias expression.
4639
4640    Example:
4641        >>> alias_('foo', 'bar').sql()
4642        'foo AS bar'
4643
4644        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4645        '(SELECT 1, 2) AS bar(a, b)'
4646
4647    Args:
4648        expression: the SQL code strings to parse.
4649            If an Expression instance is passed, this is used as-is.
4650        alias: the alias name to use. If the name has
4651            special characters it is quoted.
4652        table: Whether or not to create a table alias, can also be a list of columns.
4653        quoted: whether or not to quote the alias
4654        dialect: the dialect used to parse the input expression.
4655        **opts: other options to use to parse the input expressions.
4656
4657    Returns:
4658        Alias: the aliased expression
4659    """
4660    exp = maybe_parse(expression, dialect=dialect, **opts)
4661    alias = to_identifier(alias, quoted=quoted)
4662
4663    if table:
4664        table_alias = TableAlias(this=alias)
4665        exp.set("alias", table_alias)
4666
4667        if not isinstance(table, bool):
4668            for column in table:
4669                table_alias.append("columns", to_identifier(column, quoted=quoted))
4670
4671        return exp
4672
4673    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4674    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4675    # for the complete Window expression.
4676    #
4677    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4678
4679    if "alias" in exp.arg_types and not isinstance(exp, Window):
4680        exp = exp.copy()
4681        exp.set("alias", alias)
4682        return exp
4683    return Alias(this=exp, alias=alias)
4684
4685
4686def subquery(expression, alias=None, dialect=None, **opts):
4687    """
4688    Build a subquery expression.
4689
4690    Example:
4691        >>> subquery('select x from tbl', 'bar').select('x').sql()
4692        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4693
4694    Args:
4695        expression (str | Expression): the SQL code strings to parse.
4696            If an Expression instance is passed, this is used as-is.
4697        alias (str | Expression): the alias name to use.
4698        dialect (str): the dialect used to parse the input expression.
4699        **opts: other options to use to parse the input expressions.
4700
4701    Returns:
4702        Select: a new select with the subquery expression included
4703    """
4704
4705    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4706    return Select().from_(expression, dialect=dialect, **opts)
4707
4708
4709def column(
4710    col: str | Identifier,
4711    table: t.Optional[str | Identifier] = None,
4712    db: t.Optional[str | Identifier] = None,
4713    catalog: t.Optional[str | Identifier] = None,
4714    quoted: t.Optional[bool] = None,
4715) -> Column:
4716    """
4717    Build a Column.
4718
4719    Args:
4720        col: column name
4721        table: table name
4722        db: db name
4723        catalog: catalog name
4724        quoted: whether or not to force quote each part
4725    Returns:
4726        Column: column instance
4727    """
4728    return Column(
4729        this=to_identifier(col, quoted=quoted),
4730        table=to_identifier(table, quoted=quoted),
4731        db=to_identifier(db, quoted=quoted),
4732        catalog=to_identifier(catalog, quoted=quoted),
4733    )
4734
4735
4736def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4737    """Cast an expression to a data type.
4738
4739    Example:
4740        >>> cast('x + 1', 'int').sql()
4741        'CAST(x + 1 AS INT)'
4742
4743    Args:
4744        expression: The expression to cast.
4745        to: The datatype to cast to.
4746
4747    Returns:
4748        A cast node.
4749    """
4750    expression = maybe_parse(expression, **opts)
4751    return Cast(this=expression, to=DataType.build(to, **opts))
4752
4753
4754def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4755    """Build a Table.
4756
4757    Args:
4758        table (str | Expression): column name
4759        db (str | Expression): db name
4760        catalog (str | Expression): catalog name
4761
4762    Returns:
4763        Table: table instance
4764    """
4765    return Table(
4766        this=to_identifier(table, quoted=quoted),
4767        db=to_identifier(db, quoted=quoted),
4768        catalog=to_identifier(catalog, quoted=quoted),
4769        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4770    )
4771
4772
4773def values(
4774    values: t.Iterable[t.Tuple[t.Any, ...]],
4775    alias: t.Optional[str] = None,
4776    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4777) -> Values:
4778    """Build VALUES statement.
4779
4780    Example:
4781        >>> values([(1, '2')]).sql()
4782        "VALUES (1, '2')"
4783
4784    Args:
4785        values: values statements that will be converted to SQL
4786        alias: optional alias
4787        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4788         If either are provided then an alias is also required.
4789         If a dictionary is provided then the first column of the values will be casted to the expected type
4790         in order to help with type inference.
4791
4792    Returns:
4793        Values: the Values expression object
4794    """
4795    if columns and not alias:
4796        raise ValueError("Alias is required when providing columns")
4797    table_alias = (
4798        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4799        if columns
4800        else TableAlias(this=to_identifier(alias) if alias else None)
4801    )
4802    expressions = [convert(tup) for tup in values]
4803    if columns and isinstance(columns, dict):
4804        types = list(columns.values())
4805        expressions[0].set(
4806            "expressions",
4807            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4808        )
4809    return Values(
4810        expressions=expressions,
4811        alias=table_alias,
4812    )
4813
4814
4815def var(name: t.Optional[ExpOrStr]) -> Var:
4816    """Build a SQL variable.
4817
4818    Example:
4819        >>> repr(var('x'))
4820        '(VAR this: x)'
4821
4822        >>> repr(var(column('x', table='y')))
4823        '(VAR this: x)'
4824
4825    Args:
4826        name: The name of the var or an expression who's name will become the var.
4827
4828    Returns:
4829        The new variable node.
4830    """
4831    if not name:
4832        raise ValueError("Cannot convert empty name into var.")
4833
4834    if isinstance(name, Expression):
4835        name = name.name
4836    return Var(this=name)
4837
4838
4839def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4840    """Build ALTER TABLE... RENAME... expression
4841
4842    Args:
4843        old_name: The old name of the table
4844        new_name: The new name of the table
4845
4846    Returns:
4847        Alter table expression
4848    """
4849    old_table = to_table(old_name)
4850    new_table = to_table(new_name)
4851    return AlterTable(
4852        this=old_table,
4853        actions=[
4854            RenameTable(this=new_table),
4855        ],
4856    )
4857
4858
4859def convert(value) -> Expression:
4860    """Convert a python value into an expression object.
4861
4862    Raises an error if a conversion is not possible.
4863
4864    Args:
4865        value (Any): a python object
4866
4867    Returns:
4868        Expression: the equivalent expression object
4869    """
4870    if isinstance(value, Expression):
4871        return value
4872    if value is None:
4873        return NULL
4874    if isinstance(value, bool):
4875        return Boolean(this=value)
4876    if isinstance(value, str):
4877        return Literal.string(value)
4878    if isinstance(value, float) and math.isnan(value):
4879        return NULL
4880    if isinstance(value, numbers.Number):
4881        return Literal.number(value)
4882    if isinstance(value, tuple):
4883        return Tuple(expressions=[convert(v) for v in value])
4884    if isinstance(value, list):
4885        return Array(expressions=[convert(v) for v in value])
4886    if isinstance(value, dict):
4887        return Map(
4888            keys=[convert(k) for k in value],
4889            values=[convert(v) for v in value.values()],
4890        )
4891    if isinstance(value, datetime.datetime):
4892        datetime_literal = Literal.string(
4893            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4894        )
4895        return TimeStrToTime(this=datetime_literal)
4896    if isinstance(value, datetime.date):
4897        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4898        return DateStrToDate(this=date_literal)
4899    raise ValueError(f"Cannot convert {value}")
4900
4901
4902def replace_children(expression, fun, *args, **kwargs):
4903    """
4904    Replace children of an expression with the result of a lambda fun(child) -> exp.
4905    """
4906    for k, v in expression.args.items():
4907        is_list_arg = type(v) is list
4908
4909        child_nodes = v if is_list_arg else [v]
4910        new_child_nodes = []
4911
4912        for cn in child_nodes:
4913            if isinstance(cn, Expression):
4914                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4915                    new_child_nodes.append(child_node)
4916                    child_node.parent = expression
4917                    child_node.arg_key = k
4918            else:
4919                new_child_nodes.append(cn)
4920
4921        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
4922
4923
4924def column_table_names(expression):
4925    """
4926    Return all table names referenced through columns in an expression.
4927
4928    Example:
4929        >>> import sqlglot
4930        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4931        ['c', 'a']
4932
4933    Args:
4934        expression (sqlglot.Expression): expression to find table names
4935
4936    Returns:
4937        list: A list of unique names
4938    """
4939    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))
4940
4941
4942def table_name(table) -> str:
4943    """Get the full name of a table as a string.
4944
4945    Args:
4946        table (exp.Table | str): table expression node or string.
4947
4948    Examples:
4949        >>> from sqlglot import exp, parse_one
4950        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4951        'a.b.c'
4952
4953    Returns:
4954        The table name.
4955    """
4956
4957    table = maybe_parse(table, into=Table)
4958
4959    if not table:
4960        raise ValueError(f"Cannot parse {table}")
4961
4962    return ".".join(
4963        part
4964        for part in (
4965            table.text("catalog"),
4966            table.text("db"),
4967            table.name,
4968        )
4969        if part
4970    )
4971
4972
4973def replace_tables(expression, mapping):
4974    """Replace all tables in expression according to the mapping.
4975
4976    Args:
4977        expression (sqlglot.Expression): expression node to be transformed and replaced.
4978        mapping (Dict[str, str]): mapping of table names.
4979
4980    Examples:
4981        >>> from sqlglot import exp, parse_one
4982        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4983        'SELECT * FROM c'
4984
4985    Returns:
4986        The mapped expression.
4987    """
4988
4989    def _replace_tables(node):
4990        if isinstance(node, Table):
4991            new_name = mapping.get(table_name(node))
4992            if new_name:
4993                return to_table(
4994                    new_name,
4995                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4996                )
4997        return node
4998
4999    return expression.transform(_replace_tables)
5000
5001
5002def replace_placeholders(expression, *args, **kwargs):
5003    """Replace placeholders in an expression.
5004
5005    Args:
5006        expression (sqlglot.Expression): expression node to be transformed and replaced.
5007        args: positional names that will substitute unnamed placeholders in the given order.
5008        kwargs: keyword arguments that will substitute named placeholders.
5009
5010    Examples:
5011        >>> from sqlglot import exp, parse_one
5012        >>> replace_placeholders(
5013        ...     parse_one("select * from :tbl where ? = ?"),
5014        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5015        ... ).sql()
5016        "SELECT * FROM foo WHERE str_col = 'b'"
5017
5018    Returns:
5019        The mapped expression.
5020    """
5021
5022    def _replace_placeholders(node, args, **kwargs):
5023        if isinstance(node, Placeholder):
5024            if node.name:
5025                new_name = kwargs.get(node.name)
5026                if new_name:
5027                    return convert(new_name)
5028            else:
5029                try:
5030                    return convert(next(args))
5031                except StopIteration:
5032                    pass
5033        return node
5034
5035    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5036
5037
5038def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5039    """Transforms an expression by expanding all referenced sources into subqueries.
5040
5041    Examples:
5042        >>> from sqlglot import parse_one
5043        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5044        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5045
5046    Args:
5047        expression: The expression to expand.
5048        sources: A dictionary of name to Subqueryables.
5049        copy: Whether or not to copy the expression during transformation. Defaults to True.
5050
5051    Returns:
5052        The transformed expression.
5053    """
5054
5055    def _expand(node: Expression):
5056        if isinstance(node, Table):
5057            name = table_name(node)
5058            source = sources.get(name)
5059            if source:
5060                subquery = source.subquery(node.alias or name)
5061                subquery.comments = [f"source: {name}"]
5062                return subquery
5063        return node
5064
5065    return expression.transform(_expand, copy=copy)
5066
5067
5068def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5069    """
5070    Returns a Func expression.
5071
5072    Examples:
5073        >>> func("abs", 5).sql()
5074        'ABS(5)'
5075
5076        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5077        'CAST(5 AS DOUBLE)'
5078
5079    Args:
5080        name: the name of the function to build.
5081        args: the args used to instantiate the function of interest.
5082        dialect: the source dialect.
5083        kwargs: the kwargs used to instantiate the function of interest.
5084
5085    Note:
5086        The arguments `args` and `kwargs` are mutually exclusive.
5087
5088    Returns:
5089        An instance of the function of interest, or an anonymous function, if `name` doesn't
5090        correspond to an existing `sqlglot.expressions.Func` class.
5091    """
5092    if args and kwargs:
5093        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5094
5095    from sqlglot.dialects.dialect import Dialect
5096
5097    converted = [convert(arg) for arg in args]
5098    kwargs = {key: convert(value) for key, value in kwargs.items()}
5099
5100    parser = Dialect.get_or_raise(dialect)().parser()
5101    from_args_list = parser.FUNCTIONS.get(name.upper())
5102
5103    if from_args_list:
5104        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5105    else:
5106        kwargs = kwargs or {"expressions": converted}
5107        function = Anonymous(this=name, **kwargs)
5108
5109    for error_message in function.error_messages(converted):
5110        raise ValueError(error_message)
5111
5112    return function
5113
5114
5115def true():
5116    """
5117    Returns a true Boolean expression.
5118    """
5119    return Boolean(this=True)
5120
5121
5122def false():
5123    """
5124    Returns a false Boolean expression.
5125    """
5126    return Boolean(this=False)
5127
5128
5129def null():
5130    """
5131    Returns a Null expression.
5132    """
5133    return Null()
5134
5135
5136# TODO: deprecate this
5137TRUE = Boolean(this=True)
5138FALSE = Boolean(this=False)
5139NULL = Null()
class Expression:
 57class Expression(metaclass=_Expression):
 58    """
 59    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 60    context, such as its child expressions, their names (arg keys), and whether a given child expression
 61    is optional or not.
 62
 63    Attributes:
 64        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 65            and representing expressions as strings.
 66        arg_types: determines what arguments (child nodes) are supported by an expression. It
 67            maps arg keys to booleans that indicate whether the corresponding args are optional.
 68
 69    Example:
 70        >>> class Foo(Expression):
 71        ...     arg_types = {"this": True, "expression": False}
 72
 73        The above definition informs us that Foo is an Expression that requires an argument called
 74        "this" and may also optionally receive an argument called "expression".
 75
 76    Args:
 77        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 78        parent: a reference to the parent expression (or None, in case of root expressions).
 79        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 80            uses to refer to it.
 81        comments: a list of comments that are associated with a given expression. This is used in
 82            order to preserve comments when transpiling SQL code.
 83        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 84            optimizer, in order to enable some transformations that require type information.
 85    """
 86
 87    key = "expression"
 88    arg_types = {"this": True}
 89    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 90
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
102
103    def __eq__(self, other) -> bool:
104        return type(self) is type(other) and hash(self) == hash(other)
105
106    @property
107    def hashable_args(self) -> t.Any:
108        args = (self.args.get(k) for k in self.arg_types)
109
110        return tuple(
111            (tuple(_norm_arg(a) for a in arg) if arg else None)
112            if type(arg) is list
113            else (_norm_arg(arg) if arg is not None and arg is not False else None)
114            for arg in args
115        )
116
117    def __hash__(self) -> int:
118        if self._hash is not None:
119            return self._hash
120
121        return hash((self.__class__, self.hashable_args))
122
123    @property
124    def this(self):
125        """
126        Retrieves the argument with key "this".
127        """
128        return self.args.get("this")
129
130    @property
131    def expression(self):
132        """
133        Retrieves the argument with key "expression".
134        """
135        return self.args.get("expression")
136
137    @property
138    def expressions(self):
139        """
140        Retrieves the argument with key "expressions".
141        """
142        return self.args.get("expressions") or []
143
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""
157
158    @property
159    def is_string(self) -> bool:
160        """
161        Checks whether a Literal expression is a string.
162        """
163        return isinstance(self, Literal) and self.args["is_string"]
164
165    @property
166    def is_number(self) -> bool:
167        """
168        Checks whether a Literal expression is a number.
169        """
170        return isinstance(self, Literal) and not self.args["is_string"]
171
172    @property
173    def is_int(self) -> bool:
174        """
175        Checks whether a Literal expression is an integer.
176        """
177        if self.is_number:
178            try:
179                int(self.name)
180                return True
181            except ValueError:
182                pass
183        return False
184
185    @property
186    def is_star(self) -> bool:
187        """Checks whether an expression is a star."""
188        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
189
190    @property
191    def alias(self) -> str:
192        """
193        Returns the alias of the expression, or an empty string if it's not aliased.
194        """
195        if isinstance(self.args.get("alias"), TableAlias):
196            return self.args["alias"].name
197        return self.text("alias")
198
199    @property
200    def name(self) -> str:
201        return self.text("this")
202
203    @property
204    def alias_or_name(self):
205        return self.alias or self.name
206
207    @property
208    def output_name(self):
209        """
210        Name of the output column if this expression is a selection.
211
212        If the Expression has no output name, an empty string is returned.
213
214        Example:
215            >>> from sqlglot import parse_one
216            >>> parse_one("SELECT a").expressions[0].output_name
217            'a'
218            >>> parse_one("SELECT b AS c").expressions[0].output_name
219            'c'
220            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
221            ''
222        """
223        return ""
224
225    @property
226    def type(self) -> t.Optional[DataType]:
227        return self._type
228
229    @type.setter
230    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
231        if dtype and not isinstance(dtype, DataType):
232            dtype = DataType.build(dtype)
233        self._type = dtype  # type: ignore
234
235    @property
236    def meta(self) -> t.Dict[str, t.Any]:
237        if self._meta is None:
238            self._meta = {}
239        return self._meta
240
241    def __deepcopy__(self, memo):
242        copy = self.__class__(**deepcopy(self.args))
243        if self.comments is not None:
244            copy.comments = deepcopy(self.comments)
245
246        if self._type is not None:
247            copy._type = self._type.copy()
248
249        if self._meta is not None:
250            copy._meta = deepcopy(self._meta)
251
252        return copy
253
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new
261
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)
274
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)
285
286    def _set_parent(self, arg_key, value):
287        if hasattr(value, "parent"):
288            value.parent = self
289            value.arg_key = arg_key
290        elif type(value) is list:
291            for v in value:
292                if hasattr(v, "parent"):
293                    v.parent = self
294                    v.arg_key = arg_key
295
296    @property
297    def depth(self):
298        """
299        Returns the depth of this tree.
300        """
301        if self.parent:
302            return self.parent.depth + 1
303        return 0
304
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs
315
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)
328
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression
343
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)
358
359    @property
360    def parent_select(self):
361        """
362        Returns the parent select statement.
363        """
364        return self.find_ancestor(Select)
365
366    @property
367    def same_parent(self):
368        """Returns if the parent is the same class as itself."""
369        return type(self.parent) is self.__class__
370
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression
379
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)
397
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)
413
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))
433
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression
442
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self
450
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())
456
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node
466
467    def __str__(self):
468        return self.sql()
469
470    def __repr__(self):
471        return self._to_s()
472
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)
487
488    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
489        indent = "" if not level else "\n"
490        indent += "".join(["  "] * level)
491        left = f"({self.key.upper()} "
492
493        args: t.Dict[str, t.Any] = {
494            k: ", ".join(
495                v._to_s(hide_missing=hide_missing, level=level + 1)
496                if hasattr(v, "_to_s")
497                else str(v)
498                for v in ensure_list(vs)
499                if v is not None
500            )
501            for k, vs in self.args.items()
502        }
503        args["comments"] = self.comments
504        args["type"] = self.type
505        args = {k: v for k, v in args.items() if v or not hide_missing}
506
507        right = ", ".join(f"{k}: {v}" for k, v in args.items())
508        right += ")"
509
510        return indent + left + right
511
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node
538
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression
565
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self
575
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self
592
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors
626
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)
634
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Expression(**args: Any)
 91    def __init__(self, **args: t.Any):
 92        self.args: t.Dict[str, t.Any] = args
 93        self.parent: t.Optional[Expression] = None
 94        self.arg_key: t.Optional[str] = None
 95        self.comments: t.Optional[t.List[str]] = None
 96        self._type: t.Optional[DataType] = None
 97        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 98        self._hash: t.Optional[int] = None
 99
100        for arg_key, value in self.args.items():
101            self._set_parent(arg_key, value)
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
144    def text(self, key) -> str:
145        """
146        Returns a textual representation of the argument corresponding to "key". This can only be used
147        for args that are strings or leaf Expression instances, such as identifiers and literals.
148        """
149        field = self.args.get(key)
150        if isinstance(field, str):
151            return field
152        if isinstance(field, (Identifier, Literal, Var)):
153            return field.this
154        if isinstance(field, (Star, Null)):
155            return field.name
156        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def copy(self):
254    def copy(self):
255        """
256        Returns a deep copy of the expression.
257        """
258        new = deepcopy(self)
259        new.parent = self.parent
260        return new

Returns a deep copy of the expression.

def append(self, arg_key, value):
262    def append(self, arg_key, value):
263        """
264        Appends value to arg_key if it's a list or sets it as a new list.
265
266        Args:
267            arg_key (str): name of the list expression arg
268            value (Any): value to append to the list
269        """
270        if not isinstance(self.args.get(arg_key), list):
271            self.args[arg_key] = []
272        self.args[arg_key].append(value)
273        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key, value):
275    def set(self, arg_key, value):
276        """
277        Sets `arg_key` to `value`.
278
279        Args:
280            arg_key (str): name of the expression arg.
281            value: value to set the arg to.
282        """
283        self.args[arg_key] = value
284        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
305    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
306        """Yields the key and expression for all arguments, exploding list args."""
307        for k, vs in self.args.items():
308            if type(vs) is list:
309                for v in vs:
310                    if hasattr(v, "parent"):
311                        yield k, v
312            else:
313                if hasattr(vs, "parent"):
314                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs=True) -> Optional[~E]:
316    def find(self, *expression_types: t.Type[E], bfs=True) -> E | None:
317        """
318        Returns the first node in this tree which matches at least one of
319        the specified types.
320
321        Args:
322            expression_types: the expression type(s) to match.
323
324        Returns:
325            The node which matches the criteria or None if no such node was found.
326        """
327        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs=True) -> Iterator[~E]:
329    def find_all(self, *expression_types: t.Type[E], bfs=True) -> t.Iterator[E]:
330        """
331        Returns a generator object which visits all nodes in this tree and only
332        yields those that match at least one of the specified expression types.
333
334        Args:
335            expression_types: the expression type(s) to match.
336
337        Returns:
338            The generator object.
339        """
340        for expression, *_ in self.walk(bfs=bfs):
341            if isinstance(expression, expression_types):
342                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
344    def find_ancestor(self, *expression_types: t.Type[E]) -> E | None:
345        """
346        Returns a nearest parent matching expression_types.
347
348        Args:
349            expression_types: the expression type(s) to match.
350
351        Returns:
352            The parent node.
353        """
354        ancestor = self.parent
355        while ancestor and not isinstance(ancestor, expression_types):
356            ancestor = ancestor.parent
357        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select

Returns the parent select statement.

same_parent

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
371    def root(self) -> Expression:
372        """
373        Returns the root expression of this tree.
374        """
375        expression = self
376        while expression.parent:
377            expression = expression.parent
378        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
380    def walk(self, bfs=True, prune=None):
381        """
382        Returns a generator object which visits all nodes in this tree.
383
384        Args:
385            bfs (bool): if set to True the BFS traversal order will be applied,
386                otherwise the DFS traversal will be used instead.
387            prune ((node, parent, arg_key) -> bool): callable that returns True if
388                the generator should stop traversing this branch of the tree.
389
390        Returns:
391            the generator object.
392        """
393        if bfs:
394            yield from self.bfs(prune=prune)
395        else:
396            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
398    def dfs(self, parent=None, key=None, prune=None):
399        """
400        Returns a generator object which visits all nodes in this tree in
401        the DFS (Depth-first) order.
402
403        Returns:
404            The generator object.
405        """
406        parent = parent or self.parent
407        yield self, parent, key
408        if prune and prune(self, parent, key):
409            return
410
411        for k, v in self.iter_expressions():
412            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
414    def bfs(self, prune=None):
415        """
416        Returns a generator object which visits all nodes in this tree in
417        the BFS (Breadth-first) order.
418
419        Returns:
420            The generator object.
421        """
422        queue = deque([(self, self.parent, None)])
423
424        while queue:
425            item, parent, key = queue.popleft()
426
427            yield item, parent, key
428            if prune and prune(item, parent, key):
429                continue
430
431            for k, v in item.iter_expressions():
432                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
434    def unnest(self):
435        """
436        Returns the first non parenthesis child or self.
437        """
438        expression = self
439        while type(expression) is Paren:
440            expression = expression.this
441        return expression

Returns the first non parenthesis child or self.

def unalias(self):
443    def unalias(self):
444        """
445        Returns the inner expression if this is an Alias.
446        """
447        if isinstance(self, Alias):
448            return self.this
449        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
451    def unnest_operands(self):
452        """
453        Returns unnested operands as a tuple.
454        """
455        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
457    def flatten(self, unnest=True):
458        """
459        Returns a generator which yields child nodes who's parents are the same class.
460
461        A AND B AND C -> [A, B, C]
462        """
463        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
464            if not type(node) is self.__class__:
465                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
473    def sql(self, dialect: DialectType = None, **opts) -> str:
474        """
475        Returns SQL string representation of this tree.
476
477        Args:
478            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
479            opts: other `sqlglot.generator.Generator` options.
480
481        Returns:
482            The SQL string.
483        """
484        from sqlglot.dialects import Dialect
485
486        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
512    def transform(self, fun, *args, copy=True, **kwargs):
513        """
514        Recursively visits all tree nodes (excluding already transformed ones)
515        and applies the given transformation function to each node.
516
517        Args:
518            fun (function): a function which takes a node as an argument and returns a
519                new transformed node or the same node without modifications. If the function
520                returns None, then the corresponding node will be removed from the syntax tree.
521            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
522                modified in place.
523
524        Returns:
525            The transformed tree.
526        """
527        node = self.copy() if copy else self
528        new_node = fun(node, *args, **kwargs)
529
530        if new_node is None or not isinstance(new_node, Expression):
531            return new_node
532        if new_node is not node:
533            new_node.parent = node.parent
534            return new_node
535
536        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
537        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
539    def replace(self, expression):
540        """
541        Swap out this expression with a new expression.
542
543        For example::
544
545            >>> tree = Select().select("x").from_("tbl")
546            >>> tree.find(Column).replace(Column(this="y"))
547            (COLUMN this: y)
548            >>> tree.sql()
549            'SELECT y FROM tbl'
550
551        Args:
552            expression (Expression|None): new node
553
554        Returns:
555            The new expression or expressions.
556        """
557        if not self.parent:
558            return expression
559
560        parent = self.parent
561        self.parent = None
562
563        replace_children(parent, lambda child: expression if child is self else child)
564        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression (Expression|None): new node
Returns:

The new expression or expressions.

def pop(self):
566    def pop(self):
567        """
568        Remove this expression from its AST.
569
570        Returns:
571            The popped expression.
572        """
573        self.replace(None)
574        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_):
576    def assert_is(self, type_):
577        """
578        Assert that this `Expression` is an instance of `type_`.
579
580        If it is NOT an instance of `type_`, this raises an assertion error.
581        Otherwise, this returns this expression.
582
583        Examples:
584            This is useful for type security in chained expressions:
585
586            >>> import sqlglot
587            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
588            'SELECT x, z FROM y'
589        """
590        assert isinstance(self, type_)
591        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
593    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
594        """
595        Checks if this expression is valid (e.g. all mandatory args are set).
596
597        Args:
598            args: a sequence of values that were used to instantiate a Func expression. This is used
599                to check that the provided arguments don't exceed the function argument limit.
600
601        Returns:
602            A list of error messages for all possible errors that were found.
603        """
604        errors: t.List[str] = []
605
606        for k in self.args:
607            if k not in self.arg_types:
608                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
609        for k, mandatory in self.arg_types.items():
610            v = self.args.get(k)
611            if mandatory and (v is None or (isinstance(v, list) and not v)):
612                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
613
614        if (
615            args
616            and isinstance(self, Func)
617            and len(args) > len(self.arg_types)
618            and not self.is_var_len_args
619        ):
620            errors.append(
621                f"The number of provided arguments ({len(args)}) is greater than "
622                f"the maximum number of supported arguments ({len(self.arg_types)})"
623            )
624
625        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
627    def dump(self):
628        """
629        Dump this Expression to a JSON-serializable dict.
630        """
631        from sqlglot.serde import dump
632
633        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
635    @classmethod
636    def load(cls, obj):
637        """
638        Load a dict (as returned by `Expression.dump`) into an Expression instance.
639        """
640        from sqlglot.serde import load
641
642        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

class Condition(Expression):
653class Condition(Expression):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)
672
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)
691
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)
def and_(self, *expressions, dialect=None, **opts):
654    def and_(self, *expressions, dialect=None, **opts):
655        """
656        AND this condition with one or multiple expressions.
657
658        Example:
659            >>> condition("x=1").and_("y=1").sql()
660            'x = 1 AND y = 1'
661
662        Args:
663            *expressions (str | Expression): the SQL code strings to parse.
664                If an `Expression` instance is passed, it will be used as-is.
665            dialect (str): the dialect used to parse the input expression.
666            opts (kwargs): other options to use to parse the input expressions.
667
668        Returns:
669            And: the new condition.
670        """
671        return and_(self, *expressions, dialect=dialect, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

And: the new condition.

def or_(self, *expressions, dialect=None, **opts):
673    def or_(self, *expressions, dialect=None, **opts):
674        """
675        OR this condition with one or multiple expressions.
676
677        Example:
678            >>> condition("x=1").or_("y=1").sql()
679            'x = 1 OR y = 1'
680
681        Args:
682            *expressions (str | Expression): the SQL code strings to parse.
683                If an `Expression` instance is passed, it will be used as-is.
684            dialect (str): the dialect used to parse the input expression.
685            opts (kwargs): other options to use to parse the input expressions.
686
687        Returns:
688            Or: the new condition.
689        """
690        return or_(self, *expressions, dialect=dialect, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Or: the new condition.

def not_(self):
692    def not_(self):
693        """
694        Wrap this condition with NOT.
695
696        Example:
697            >>> condition("x=1").not_().sql()
698            'NOT x = 1'
699
700        Returns:
701            Not: the new condition.
702        """
703        return not_(self)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Returns:

Not: the new condition.

class Predicate(Condition):
706class Predicate(Condition):
707    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

class DerivedTable(Expression):
710class DerivedTable(Expression):
711    @property
712    def alias_column_names(self):
713        table_alias = self.args.get("alias")
714        if not table_alias:
715            return []
716        column_list = table_alias.assert_is(TableAlias).args.get("columns") or []
717        return [c.name for c in column_list]
718
719    @property
720    def selects(self):
721        alias = self.args.get("alias")
722
723        if alias:
724            return alias.columns
725        return []
726
727    @property
728    def named_selects(self):
729        return [select.output_name for select in self.selects]
class Unionable(Expression):
732class Unionable(Expression):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
752
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
772
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union(self, expression, distinct=True, dialect=None, **opts):
733    def union(self, expression, distinct=True, dialect=None, **opts):
734        """
735        Builds a UNION expression.
736
737        Example:
738            >>> import sqlglot
739            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
740            'SELECT * FROM foo UNION SELECT * FROM bla'
741
742        Args:
743            expression (str | Expression): the SQL code string.
744                If an `Expression` instance is passed, it will be used as-is.
745            distinct (bool): set the DISTINCT flag if and only if this is true.
746            dialect (str): the dialect used to parse the input expression.
747            opts (kwargs): other options to use to parse the input expressions.
748        Returns:
749            Union: the Union expression.
750        """
751        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the Union expression.

def intersect(self, expression, distinct=True, dialect=None, **opts):
753    def intersect(self, expression, distinct=True, dialect=None, **opts):
754        """
755        Builds an INTERSECT expression.
756
757        Example:
758            >>> import sqlglot
759            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
760            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
761
762        Args:
763            expression (str | Expression): the SQL code string.
764                If an `Expression` instance is passed, it will be used as-is.
765            distinct (bool): set the DISTINCT flag if and only if this is true.
766            dialect (str): the dialect used to parse the input expression.
767            opts (kwargs): other options to use to parse the input expressions.
768        Returns:
769            Intersect: the Intersect expression
770        """
771        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the Intersect expression

def except_(self, expression, distinct=True, dialect=None, **opts):
773    def except_(self, expression, distinct=True, dialect=None, **opts):
774        """
775        Builds an EXCEPT expression.
776
777        Example:
778            >>> import sqlglot
779            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
780            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
781
782        Args:
783            expression (str | Expression): the SQL code string.
784                If an `Expression` instance is passed, it will be used as-is.
785            distinct (bool): set the DISTINCT flag if and only if this is true.
786            dialect (str): the dialect used to parse the input expression.
787            opts (kwargs): other options to use to parse the input expressions.
788        Returns:
789            Except: the Except expression
790        """
791        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression (str | Expression): the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the Except expression

class UDTF(DerivedTable, Unionable):
794class UDTF(DerivedTable, Unionable):
795    pass
class Cache(Expression):
798class Cache(Expression):
799    arg_types = {
800        "with": False,
801        "this": True,
802        "lazy": False,
803        "options": False,
804        "expression": False,
805    }
class Uncache(Expression):
808class Uncache(Expression):
809    arg_types = {"this": True, "exists": False}
class Create(Expression):
812class Create(Expression):
813    arg_types = {
814        "with": False,
815        "this": True,
816        "kind": True,
817        "expression": False,
818        "exists": False,
819        "properties": False,
820        "replace": False,
821        "unique": False,
822        "volatile": False,
823        "indexes": False,
824        "no_schema_binding": False,
825        "begin": False,
826    }
class Describe(Expression):
829class Describe(Expression):
830    arg_types = {"this": True, "kind": False}
class Pragma(Expression):
833class Pragma(Expression):
834    pass
class Set(Expression):
837class Set(Expression):
838    arg_types = {"expressions": False}
class SetItem(Expression):
841class SetItem(Expression):
842    arg_types = {
843        "this": False,
844        "expressions": False,
845        "kind": False,
846        "collate": False,  # MySQL SET NAMES statement
847        "global": False,
848    }
class Show(Expression):
851class Show(Expression):
852    arg_types = {
853        "this": True,
854        "target": False,
855        "offset": False,
856        "limit": False,
857        "like": False,
858        "where": False,
859        "db": False,
860        "full": False,
861        "mutex": False,
862        "query": False,
863        "channel": False,
864        "global": False,
865        "log": False,
866        "position": False,
867        "types": False,
868    }
class UserDefinedFunction(Expression):
871class UserDefinedFunction(Expression):
872    arg_types = {"this": True, "expressions": False, "wrapped": False}
class CharacterSet(Expression):
875class CharacterSet(Expression):
876    arg_types = {"this": True, "default": False}
class With(Expression):
879class With(Expression):
880    arg_types = {"expressions": True, "recursive": False}
881
882    @property
883    def recursive(self) -> bool:
884        return bool(self.args.get("recursive"))
class WithinGroup(Expression):
887class WithinGroup(Expression):
888    arg_types = {"this": True, "expression": False}
class CTE(DerivedTable):
891class CTE(DerivedTable):
892    arg_types = {"this": True, "alias": True}
class TableAlias(Expression):
895class TableAlias(Expression):
896    arg_types = {"this": False, "columns": False}
897
898    @property
899    def columns(self):
900        return self.args.get("columns") or []
class BitString(Condition):
903class BitString(Condition):
904    pass
class HexString(Condition):
907class HexString(Condition):
908    pass
class ByteString(Condition):
911class ByteString(Condition):
912    pass
class Column(Condition):
915class Column(Condition):
916    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
917
918    @property
919    def table(self) -> str:
920        return self.text("table")
921
922    @property
923    def db(self) -> str:
924        return self.text("db")
925
926    @property
927    def catalog(self) -> str:
928        return self.text("catalog")
929
930    @property
931    def output_name(self) -> str:
932        return self.name
933
934    @property
935    def parts(self) -> t.List[Identifier]:
936        """Return the parts of a column in order catalog, db, table, name."""
937        return [part for part in reversed(list(self.args.values())) if part]
938
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
939    def to_dot(self) -> Dot:
940        """Converts the column into a dot expression."""
941        parts = self.parts
942        parent = self.parent
943
944        while parent:
945            if isinstance(parent, Dot):
946                parts.append(parent.expression)
947            parent = parent.parent
948
949        return Dot.build(parts)

Converts the column into a dot expression.

class ColumnPosition(Expression):
952class ColumnPosition(Expression):
953    arg_types = {"this": False, "position": True}
class ColumnDef(Expression):
956class ColumnDef(Expression):
957    arg_types = {
958        "this": True,
959        "kind": False,
960        "constraints": False,
961        "exists": False,
962        "position": False,
963    }
class AlterColumn(Expression):
966class AlterColumn(Expression):
967    arg_types = {
968        "this": True,
969        "dtype": False,
970        "collate": False,
971        "using": False,
972        "default": False,
973        "drop": False,
974    }
class RenameTable(Expression):
977class RenameTable(Expression):
978    pass
class SetTag(Expression):
981class SetTag(Expression):
982    arg_types = {"expressions": True, "unset": False}
class Comment(Expression):
985class Comment(Expression):
986    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
class ColumnConstraint(Expression):
989class ColumnConstraint(Expression):
990    arg_types = {"this": False, "kind": True}
class ColumnConstraintKind(Expression):
993class ColumnConstraintKind(Expression):
994    pass
class AutoIncrementColumnConstraint(ColumnConstraintKind):
997class AutoIncrementColumnConstraint(ColumnConstraintKind):
998    pass
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1001class CaseSpecificColumnConstraint(ColumnConstraintKind):
1002    arg_types = {"not_": True}
class CharacterSetColumnConstraint(ColumnConstraintKind):
1005class CharacterSetColumnConstraint(ColumnConstraintKind):
1006    arg_types = {"this": True}
class CheckColumnConstraint(ColumnConstraintKind):
1009class CheckColumnConstraint(ColumnConstraintKind):
1010    pass
class CollateColumnConstraint(ColumnConstraintKind):
1013class CollateColumnConstraint(ColumnConstraintKind):
1014    pass
class CommentColumnConstraint(ColumnConstraintKind):
1017class CommentColumnConstraint(ColumnConstraintKind):
1018    pass
class CompressColumnConstraint(ColumnConstraintKind):
1021class CompressColumnConstraint(ColumnConstraintKind):
1022    pass
class DateFormatColumnConstraint(ColumnConstraintKind):
1025class DateFormatColumnConstraint(ColumnConstraintKind):
1026    arg_types = {"this": True}
class DefaultColumnConstraint(ColumnConstraintKind):
1029class DefaultColumnConstraint(ColumnConstraintKind):
1030    pass
class EncodeColumnConstraint(ColumnConstraintKind):
1033class EncodeColumnConstraint(ColumnConstraintKind):
1034    pass
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1037class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1038    # this: True -> ALWAYS, this: False -> BY DEFAULT
1039    arg_types = {
1040        "this": False,
1041        "start": False,
1042        "increment": False,
1043        "minvalue": False,
1044        "maxvalue": False,
1045        "cycle": False,
1046    }
class InlineLengthColumnConstraint(ColumnConstraintKind):
1049class InlineLengthColumnConstraint(ColumnConstraintKind):
1050    pass
class NotNullColumnConstraint(ColumnConstraintKind):
1053class NotNullColumnConstraint(ColumnConstraintKind):
1054    arg_types = {"allow_null": False}
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1057class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1058    arg_types = {"desc": False}
class TitleColumnConstraint(ColumnConstraintKind):
1061class TitleColumnConstraint(ColumnConstraintKind):
1062    pass
class UniqueColumnConstraint(ColumnConstraintKind):
1065class UniqueColumnConstraint(ColumnConstraintKind):
1066    arg_types: t.Dict[str, t.Any] = {}
class UppercaseColumnConstraint(ColumnConstraintKind):
1069class UppercaseColumnConstraint(ColumnConstraintKind):
1070    arg_types: t.Dict[str, t.Any] = {}
class PathColumnConstraint(ColumnConstraintKind):
1073class PathColumnConstraint(ColumnConstraintKind):
1074    pass
class Constraint(Expression):
1077class Constraint(Expression):
1078    arg_types = {"this": True, "expressions": True}
class Delete(Expression):
1081class Delete(Expression):
1082    arg_types = {"with": False, "this": False, "using": False, "where": False, "returning": False}
1083
1084    def delete(
1085        self,
1086        table: ExpOrStr,
1087        dialect: DialectType = None,
1088        copy: bool = True,
1089        **opts,
1090    ) -> Delete:
1091        """
1092        Create a DELETE expression or replace the table on an existing DELETE expression.
1093
1094        Example:
1095            >>> delete("tbl").sql()
1096            'DELETE FROM tbl'
1097
1098        Args:
1099            table: the table from which to delete.
1100            dialect: the dialect used to parse the input expression.
1101            copy: if `False`, modify this expression instance in-place.
1102            opts: other options to use to parse the input expressions.
1103
1104        Returns:
1105            Delete: the modified expression.
1106        """
1107        return _apply_builder(
1108            expression=table,
1109            instance=self,
1110            arg="this",
1111            dialect=dialect,
1112            into=Table,
1113            copy=copy,
1114            **opts,
1115        )
1116
1117    def where(
1118        self,
1119        *expressions: ExpOrStr,
1120        append: bool = True,
1121        dialect: DialectType = None,
1122        copy: bool = True,
1123        **opts,
1124    ) -> Delete:
1125        """
1126        Append to or set the WHERE expressions.
1127
1128        Example:
1129            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1130            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1131
1132        Args:
1133            *expressions: the SQL code strings to parse.
1134                If an `Expression` instance is passed, it will be used as-is.
1135                Multiple expressions are combined with an AND operator.
1136            append: if `True`, AND the new expressions to any existing expression.
1137                Otherwise, this resets the expression.
1138            dialect: the dialect used to parse the input expressions.
1139            copy: if `False`, modify this expression instance in-place.
1140            opts: other options to use to parse the input expressions.
1141
1142        Returns:
1143            Delete: the modified expression.
1144        """
1145        return _apply_conjunction_builder(
1146            *expressions,
1147            instance=self,
1148            arg="where",
1149            append=append,
1150            into=Where,
1151            dialect=dialect,
1152            copy=copy,
1153            **opts,
1154        )
1155
1156    def returning(
1157        self,
1158        expression: ExpOrStr,
1159        dialect: DialectType = None,
1160        copy: bool = True,
1161        **opts,
1162    ) -> Delete:
1163        """
1164        Set the RETURNING expression. Not supported by all dialects.
1165
1166        Example:
1167            >>> delete("tbl").returning("*", dialect="postgres").sql()
1168            'DELETE FROM tbl RETURNING *'
1169
1170        Args:
1171            expression: the SQL code strings to parse.
1172                If an `Expression` instance is passed, it will be used as-is.
1173            dialect: the dialect used to parse the input expressions.
1174            copy: if `False`, modify this expression instance in-place.
1175            opts: other options to use to parse the input expressions.
1176
1177        Returns:
1178            Delete: the modified expression.
1179        """
1180        return _apply_builder(
1181            expression=expression,
1182            instance=self,
1183            arg="returning",
1184            prefix="RETURNING",
1185            dialect=dialect,
1186            copy=copy,
1187            into=Returning,
1188            **opts,
1189        )
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1084    def delete(
1085        self,
1086        table: ExpOrStr,
1087        dialect: DialectType = None,
1088        copy: bool = True,
1089        **opts,
1090    ) -> Delete:
1091        """
1092        Create a DELETE expression or replace the table on an existing DELETE expression.
1093
1094        Example:
1095            >>> delete("tbl").sql()
1096            'DELETE FROM tbl'
1097
1098        Args:
1099            table: the table from which to delete.
1100            dialect: the dialect used to parse the input expression.
1101            copy: if `False`, modify this expression instance in-place.
1102            opts: other options to use to parse the input expressions.
1103
1104        Returns:
1105            Delete: the modified expression.
1106        """
1107        return _apply_builder(
1108            expression=table,
1109            instance=self,
1110            arg="this",
1111            dialect=dialect,
1112            into=Table,
1113            copy=copy,
1114            **opts,
1115        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1117    def where(
1118        self,
1119        *expressions: ExpOrStr,
1120        append: bool = True,
1121        dialect: DialectType = None,
1122        copy: bool = True,
1123        **opts,
1124    ) -> Delete:
1125        """
1126        Append to or set the WHERE expressions.
1127
1128        Example:
1129            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1130            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1131
1132        Args:
1133            *expressions: the SQL code strings to parse.
1134                If an `Expression` instance is passed, it will be used as-is.
1135                Multiple expressions are combined with an AND operator.
1136            append: if `True`, AND the new expressions to any existing expression.
1137                Otherwise, this resets the expression.
1138            dialect: the dialect used to parse the input expressions.
1139            copy: if `False`, modify this expression instance in-place.
1140            opts: other options to use to parse the input expressions.
1141
1142        Returns:
1143            Delete: the modified expression.
1144        """
1145        return _apply_conjunction_builder(
1146            *expressions,
1147            instance=self,
1148            arg="where",
1149            append=append,
1150            into=Where,
1151            dialect=dialect,
1152            copy=copy,
1153            **opts,
1154        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1156    def returning(
1157        self,
1158        expression: ExpOrStr,
1159        dialect: DialectType = None,
1160        copy: bool = True,
1161        **opts,
1162    ) -> Delete:
1163        """
1164        Set the RETURNING expression. Not supported by all dialects.
1165
1166        Example:
1167            >>> delete("tbl").returning("*", dialect="postgres").sql()
1168            'DELETE FROM tbl RETURNING *'
1169
1170        Args:
1171            expression: the SQL code strings to parse.
1172                If an `Expression` instance is passed, it will be used as-is.
1173            dialect: the dialect used to parse the input expressions.
1174            copy: if `False`, modify this expression instance in-place.
1175            opts: other options to use to parse the input expressions.
1176
1177        Returns:
1178            Delete: the modified expression.
1179        """
1180        return _apply_builder(
1181            expression=expression,
1182            instance=self,
1183            arg="returning",
1184            prefix="RETURNING",
1185            dialect=dialect,
1186            copy=copy,
1187            into=Returning,
1188            **opts,
1189        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

class Drop(Expression):
1192class Drop(Expression):
1193    arg_types = {
1194        "this": False,
1195        "kind": False,
1196        "exists": False,
1197        "temporary": False,
1198        "materialized": False,
1199        "cascade": False,
1200        "constraints": False,
1201        "purge": False,
1202    }
class Filter(Expression):
1205class Filter(Expression):
1206    arg_types = {"this": True, "expression": True}
class Check(Expression):
1209class Check(Expression):
1210    pass
class Directory(Expression):
1213class Directory(Expression):
1214    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1215    arg_types = {"this": True, "local": False, "row_format": False}
class ForeignKey(Expression):
1218class ForeignKey(Expression):
1219    arg_types = {
1220        "expressions": True,
1221        "reference": False,
1222        "delete": False,
1223        "update": False,
1224    }
class PrimaryKey(Expression):
1227class PrimaryKey(Expression):
1228    arg_types = {"expressions": True, "options": False}
class Unique(Expression):
1231class Unique(Expression):
1232    arg_types = {"expressions": True}
class Into(Expression):
1237class Into(Expression):
1238    arg_types = {"this": True, "temporary": False, "unlogged": False}
class From(Expression):
1241class From(Expression):
1242    arg_types = {"expressions": True}
class Having(Expression):
1245class Having(Expression):
1246    pass
class Hint(Expression):
1249class Hint(Expression):
1250    arg_types = {"expressions": True}
class JoinHint(Expression):
1253class JoinHint(Expression):
1254    arg_types = {"this": True, "expressions": True}
class Identifier(Expression):
1257class Identifier(Expression):
1258    arg_types = {"this": True, "quoted": False}
1259
1260    @property
1261    def quoted(self):
1262        return bool(self.args.get("quoted"))
1263
1264    @property
1265    def hashable_args(self) -> t.Any:
1266        if self.quoted and any(char.isupper() for char in self.this):
1267            return (self.this, self.quoted)
1268        return self.this.lower()
1269
1270    @property
1271    def output_name(self):
1272        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Index(Expression):
1275class Index(Expression):
1276    arg_types = {
1277        "this": False,
1278        "table": False,
1279        "where": False,
1280        "columns": False,
1281        "unique": False,
1282        "primary": False,
1283        "amp": False,  # teradata
1284    }
class Insert(Expression):
1287class Insert(Expression):
1288    arg_types = {
1289        "with": False,
1290        "this": True,
1291        "expression": False,
1292        "returning": False,
1293        "overwrite": False,
1294        "exists": False,
1295        "partition": False,
1296        "alternative": False,
1297    }
class Returning(Expression):
1300class Returning(Expression):
1301    arg_types = {"expressions": True}
class Introducer(Expression):
1305class Introducer(Expression):
1306    arg_types = {"this": True, "expression": True}
class National(Expression):
1310class National(Expression):
1311    pass
class LoadData(Expression):
1314class LoadData(Expression):
1315    arg_types = {
1316        "this": True,
1317        "local": False,
1318        "overwrite": False,
1319        "inpath": True,
1320        "partition": False,
1321        "input_format": False,
1322        "serde": False,
1323    }
class Partition(Expression):
1326class Partition(Expression):
1327    arg_types = {"expressions": True}
class Fetch(Expression):
1330class Fetch(Expression):
1331    arg_types = {"direction": False, "count": False}
class Group(Expression):
1334class Group(Expression):
1335    arg_types = {
1336        "expressions": False,
1337        "grouping_sets": False,
1338        "cube": False,
1339        "rollup": False,
1340    }
class Lambda(Expression):
1343class Lambda(Expression):
1344    arg_types = {"this": True, "expressions": True}
class Limit(Expression):
1347class Limit(Expression):
1348    arg_types = {"this": False, "expression": True}
class Literal(Condition):
1351class Literal(Condition):
1352    arg_types = {"this": True, "is_string": True}
1353
1354    @property
1355    def hashable_args(self) -> t.Any:
1356        return (self.this, self.args.get("is_string"))
1357
1358    @classmethod
1359    def number(cls, number) -> Literal:
1360        return cls(this=str(number), is_string=False)
1361
1362    @classmethod
1363    def string(cls, string) -> Literal:
1364        return cls(this=str(string), is_string=True)
1365
1366    @property
1367    def output_name(self):
1368        return self.name
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1358    @classmethod
1359    def number(cls, number) -> Literal:
1360        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1362    @classmethod
1363    def string(cls, string) -> Literal:
1364        return cls(this=str(string), is_string=True)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Join(Expression):
1371class Join(Expression):
1372    arg_types = {
1373        "this": True,
1374        "on": False,
1375        "side": False,
1376        "kind": False,
1377        "using": False,
1378        "natural": False,
1379    }
1380
1381    @property
1382    def kind(self):
1383        return self.text("kind").upper()
1384
1385    @property
1386    def side(self):
1387        return self.text("side").upper()
1388
1389    @property
1390    def alias_or_name(self):
1391        return self.this.alias_or_name
1392
1393    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1394        """
1395        Append to or set the ON expressions.
1396
1397        Example:
1398            >>> import sqlglot
1399            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1400            'JOIN x ON y = 1'
1401
1402        Args:
1403            *expressions (str | Expression): the SQL code strings to parse.
1404                If an `Expression` instance is passed, it will be used as-is.
1405                Multiple expressions are combined with an AND operator.
1406            append (bool): if `True`, AND the new expressions to any existing expression.
1407                Otherwise, this resets the expression.
1408            dialect (str): the dialect used to parse the input expressions.
1409            copy (bool): if `False`, modify this expression instance in-place.
1410            opts (kwargs): other options to use to parse the input expressions.
1411
1412        Returns:
1413            Join: the modified join expression.
1414        """
1415        join = _apply_conjunction_builder(
1416            *expressions,
1417            instance=self,
1418            arg="on",
1419            append=append,
1420            dialect=dialect,
1421            copy=copy,
1422            **opts,
1423        )
1424
1425        if join.kind == "CROSS":
1426            join.set("kind", None)
1427
1428        return join
1429
1430    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1431        """
1432        Append to or set the USING expressions.
1433
1434        Example:
1435            >>> import sqlglot
1436            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1437            'JOIN x USING (foo, bla)'
1438
1439        Args:
1440            *expressions (str | Expression): the SQL code strings to parse.
1441                If an `Expression` instance is passed, it will be used as-is.
1442            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1443                Otherwise, this resets the expression.
1444            dialect (str): the dialect used to parse the input expressions.
1445            copy (bool): if `False`, modify this expression instance in-place.
1446            opts (kwargs): other options to use to parse the input expressions.
1447
1448        Returns:
1449            Join: the modified join expression.
1450        """
1451        join = _apply_list_builder(
1452            *expressions,
1453            instance=self,
1454            arg="using",
1455            append=append,
1456            dialect=dialect,
1457            copy=copy,
1458            **opts,
1459        )
1460
1461        if join.kind == "CROSS":
1462            join.set("kind", None)
1463
1464        return join
def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1393    def on(self, *expressions, append=True, dialect=None, copy=True, **opts):
1394        """
1395        Append to or set the ON expressions.
1396
1397        Example:
1398            >>> import sqlglot
1399            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1400            'JOIN x ON y = 1'
1401
1402        Args:
1403            *expressions (str | Expression): the SQL code strings to parse.
1404                If an `Expression` instance is passed, it will be used as-is.
1405                Multiple expressions are combined with an AND operator.
1406            append (bool): if `True`, AND the new expressions to any existing expression.
1407                Otherwise, this resets the expression.
1408            dialect (str): the dialect used to parse the input expressions.
1409            copy (bool): if `False`, modify this expression instance in-place.
1410            opts (kwargs): other options to use to parse the input expressions.
1411
1412        Returns:
1413            Join: the modified join expression.
1414        """
1415        join = _apply_conjunction_builder(
1416            *expressions,
1417            instance=self,
1418            arg="on",
1419            append=append,
1420            dialect=dialect,
1421            copy=copy,
1422            **opts,
1423        )
1424
1425        if join.kind == "CROSS":
1426            join.set("kind", None)
1427
1428        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1430    def using(self, *expressions, append=True, dialect=None, copy=True, **opts):
1431        """
1432        Append to or set the USING expressions.
1433
1434        Example:
1435            >>> import sqlglot
1436            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1437            'JOIN x USING (foo, bla)'
1438
1439        Args:
1440            *expressions (str | Expression): the SQL code strings to parse.
1441                If an `Expression` instance is passed, it will be used as-is.
1442            append (bool): if `True`, concatenate the new expressions to the existing "using" list.
1443                Otherwise, this resets the expression.
1444            dialect (str): the dialect used to parse the input expressions.
1445            copy (bool): if `False`, modify this expression instance in-place.
1446            opts (kwargs): other options to use to parse the input expressions.
1447
1448        Returns:
1449            Join: the modified join expression.
1450        """
1451        join = _apply_list_builder(
1452            *expressions,
1453            instance=self,
1454            arg="using",
1455            append=append,
1456            dialect=dialect,
1457            copy=copy,
1458            **opts,
1459        )
1460
1461        if join.kind == "CROSS":
1462            join.set("kind", None)
1463
1464        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Join: the modified join expression.

class Lateral(UDTF):
1467class Lateral(UDTF):
1468    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
class MatchRecognize(Expression):
1471class MatchRecognize(Expression):
1472    arg_types = {
1473        "partition_by": False,
1474        "order": False,
1475        "measures": False,
1476        "rows": False,
1477        "after": False,
1478        "pattern": False,
1479        "define": False,
1480    }
class Final(Expression):
1485class Final(Expression):
1486    pass
class Offset(Expression):
1489class Offset(Expression):
1490    arg_types = {"this": False, "expression": True}
class Order(Expression):
1493class Order(Expression):
1494    arg_types = {"this": False, "expressions": True}
class Cluster(Order):
1499class Cluster(Order):
1500    pass
class Distribute(Order):
1503class Distribute(Order):
1504    pass
class Sort(Order):
1507class Sort(Order):
1508    pass
class Ordered(Expression):
1511class Ordered(Expression):
1512    arg_types = {"this": True, "desc": True, "nulls_first": True}
class Property(Expression):
1515class Property(Expression):
1516    arg_types = {"this": True, "value": True}
class AfterJournalProperty(Property):
1519class AfterJournalProperty(Property):
1520    arg_types = {"no": True, "dual": False, "local": False}
class AlgorithmProperty(Property):
1523class AlgorithmProperty(Property):
1524    arg_types = {"this": True}
class AutoIncrementProperty(Property):
1527class AutoIncrementProperty(Property):
1528    arg_types = {"this": True}
class BlockCompressionProperty(Property):
1531class BlockCompressionProperty(Property):
1532    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
class CharacterSetProperty(Property):
1535class CharacterSetProperty(Property):
1536    arg_types = {"this": True, "default": True}
class ChecksumProperty(Property):
1539class ChecksumProperty(Property):
1540    arg_types = {"on": False, "default": False}
class CollateProperty(Property):
1543class CollateProperty(Property):
1544    arg_types = {"this": True}
class DataBlocksizeProperty(Property):
1547class DataBlocksizeProperty(Property):
1548    arg_types = {"size": False, "units": False, "min": False, "default": False}
class DefinerProperty(Property):
1551class DefinerProperty(Property):
1552    arg_types = {"this": True}
class DistKeyProperty(Property):
1555class DistKeyProperty(Property):
1556    arg_types = {"this": True}
class DistStyleProperty(Property):
1559class DistStyleProperty(Property):
1560    arg_types = {"this": True}
class EngineProperty(Property):
1563class EngineProperty(Property):
1564    arg_types = {"this": True}
class ExecuteAsProperty(Property):
1567class ExecuteAsProperty(Property):
1568    arg_types = {"this": True}
class ExternalProperty(Property):
1571class ExternalProperty(Property):
1572    arg_types = {"this": False}
class FallbackProperty(Property):
1575class FallbackProperty(Property):
1576    arg_types = {"no": True, "protection": False}
class FileFormatProperty(Property):
1579class FileFormatProperty(Property):
1580    arg_types = {"this": True}
class FreespaceProperty(Property):
1583class FreespaceProperty(Property):
1584    arg_types = {"this": True, "percent": False}
class InputOutputFormat(Expression):
1587class InputOutputFormat(Expression):
1588    arg_types = {"input_format": False, "output_format": False}
class IsolatedLoadingProperty(Property):
1591class IsolatedLoadingProperty(Property):
1592    arg_types = {
1593        "no": True,
1594        "concurrent": True,
1595        "for_all": True,
1596        "for_insert": True,
1597        "for_none": True,
1598    }
class JournalProperty(Property):
1601class JournalProperty(Property):
1602    arg_types = {"no": True, "dual": False, "before": False}
class LanguageProperty(Property):
1605class LanguageProperty(Property):
1606    arg_types = {"this": True}
class LikeProperty(Property):
1609class LikeProperty(Property):
1610    arg_types = {"this": True, "expressions": False}
class LocationProperty(Property):
1613class LocationProperty(Property):
1614    arg_types = {"this": True}
class LockingProperty(Property):
1617class LockingProperty(Property):
1618    arg_types = {
1619        "this": False,
1620        "kind": True,
1621        "for_or_in": True,
1622        "lock_type": True,
1623        "override": False,
1624    }
class LogProperty(Property):
1627class LogProperty(Property):
1628    arg_types = {"no": True}
class MaterializedProperty(Property):
1631class MaterializedProperty(Property):
1632    arg_types = {"this": False}
class MergeBlockRatioProperty(Property):
1635class MergeBlockRatioProperty(Property):
1636    arg_types = {"this": False, "no": False, "default": False, "percent": False}
class NoPrimaryIndexProperty(Property):
1639class NoPrimaryIndexProperty(Property):
1640    arg_types = {"this": False}
class OnCommitProperty(Property):
1643class OnCommitProperty(Property):
1644    arg_type = {"this": False}
class PartitionedByProperty(Property):
1647class PartitionedByProperty(Property):
1648    arg_types = {"this": True}
class ReturnsProperty(Property):
1651class ReturnsProperty(Property):
1652    arg_types = {"this": True, "is_table": False, "table": False}
class RowFormatDelimitedProperty(Property):
1655class RowFormatDelimitedProperty(Property):
1656    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
1657    arg_types = {
1658        "fields": False,
1659        "escaped": False,
1660        "collection_items": False,
1661        "map_keys": False,
1662        "lines": False,
1663        "null": False,
1664        "serde": False,
1665    }
class RowFormatSerdeProperty(Property):
1668class RowFormatSerdeProperty(Property):
1669    arg_types = {"this": True}
class SchemaCommentProperty(Property):
1672class SchemaCommentProperty(Property):
1673    arg_types = {"this": True}
class SerdeProperties(Property):
1676class SerdeProperties(Property):
1677    arg_types = {"expressions": True}
class SetProperty(Property):
1680class SetProperty(Property):
1681    arg_types = {"multi": True}
class SortKeyProperty(Property):
1684class SortKeyProperty(Property):
1685    arg_types = {"this": True, "compound": False}
class SqlSecurityProperty(Property):
1688class SqlSecurityProperty(Property):
1689    arg_types = {"definer": True}
class TableFormatProperty(Property):
1692class TableFormatProperty(Property):
1693    arg_types = {"this": True}
class TemporaryProperty(Property):
1696class TemporaryProperty(Property):
1697    arg_types = {"global_": True}
class TransientProperty(Property):
1700class TransientProperty(Property):
1701    arg_types = {"this": False}
class VolatilityProperty(Property):
1704class VolatilityProperty(Property):
1705    arg_types = {"this": True}
class WithDataProperty(Property):
1708class WithDataProperty(Property):
1709    arg_types = {"no": True, "statistics": False}
class WithJournalTableProperty(Property):
1712class WithJournalTableProperty(Property):
1713    arg_types = {"this": True}
class Properties(Expression):
1716class Properties(Expression):
1717    arg_types = {"expressions": True}
1718
1719    NAME_TO_PROPERTY = {
1720        "ALGORITHM": AlgorithmProperty,
1721        "AUTO_INCREMENT": AutoIncrementProperty,
1722        "CHARACTER SET": CharacterSetProperty,
1723        "COLLATE": CollateProperty,
1724        "COMMENT": SchemaCommentProperty,
1725        "DEFINER": DefinerProperty,
1726        "DISTKEY": DistKeyProperty,
1727        "DISTSTYLE": DistStyleProperty,
1728        "ENGINE": EngineProperty,
1729        "EXECUTE AS": ExecuteAsProperty,
1730        "FORMAT": FileFormatProperty,
1731        "LANGUAGE": LanguageProperty,
1732        "LOCATION": LocationProperty,
1733        "PARTITIONED_BY": PartitionedByProperty,
1734        "RETURNS": ReturnsProperty,
1735        "SORTKEY": SortKeyProperty,
1736        "TABLE_FORMAT": TableFormatProperty,
1737    }
1738
1739    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
1740
1741    # CREATE property locations
1742    # Form: schema specified
1743    #   create [POST_CREATE]
1744    #     table a [POST_NAME]
1745    #     (b int) [POST_SCHEMA]
1746    #     with ([POST_WITH])
1747    #     index (b) [POST_INDEX]
1748    #
1749    # Form: alias selection
1750    #   create [POST_CREATE]
1751    #     table a [POST_NAME]
1752    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
1753    #     index (c) [POST_INDEX]
1754    class Location(AutoName):
1755        POST_CREATE = auto()
1756        POST_NAME = auto()
1757        POST_SCHEMA = auto()
1758        POST_WITH = auto()
1759        POST_ALIAS = auto()
1760        POST_EXPRESSION = auto()
1761        POST_INDEX = auto()
1762        UNSUPPORTED = auto()
1763
1764    @classmethod
1765    def from_dict(cls, properties_dict) -> Properties:
1766        expressions = []
1767        for key, value in properties_dict.items():
1768            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1769            if property_cls:
1770                expressions.append(property_cls(this=convert(value)))
1771            else:
1772                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1773
1774        return cls(expressions=expressions)
@classmethod
def from_dict(cls, properties_dict) -> sqlglot.expressions.Properties:
1764    @classmethod
1765    def from_dict(cls, properties_dict) -> Properties:
1766        expressions = []
1767        for key, value in properties_dict.items():
1768            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
1769            if property_cls:
1770                expressions.append(property_cls(this=convert(value)))
1771            else:
1772                expressions.append(Property(this=Literal.string(key), value=convert(value)))
1773
1774        return cls(expressions=expressions)
class Properties.Location(sqlglot.helper.AutoName):
1754    class Location(AutoName):
1755        POST_CREATE = auto()
1756        POST_NAME = auto()
1757        POST_SCHEMA = auto()
1758        POST_WITH = auto()
1759        POST_ALIAS = auto()
1760        POST_EXPRESSION = auto()
1761        POST_INDEX = auto()
1762        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
1777class Qualify(Expression):
1778    pass
class Return(Expression):
1782class Return(Expression):
1783    pass
class Reference(Expression):
1786class Reference(Expression):
1787    arg_types = {"this": True, "expressions": False, "options": False}
class Tuple(Expression):
1790class Tuple(Expression):
1791    arg_types = {"expressions": False}
class Subqueryable(Unionable):
1794class Subqueryable(Unionable):
1795    def subquery(self, alias=None, copy=True) -> Subquery:
1796        """
1797        Convert this expression to an aliased expression that can be used as a Subquery.
1798
1799        Example:
1800            >>> subquery = Select().select("x").from_("tbl").subquery()
1801            >>> Select().select("x").from_(subquery).sql()
1802            'SELECT x FROM (SELECT x FROM tbl)'
1803
1804        Args:
1805            alias (str | Identifier): an optional alias for the subquery
1806            copy (bool): if `False`, modify this expression instance in-place.
1807
1808        Returns:
1809            Alias: the subquery
1810        """
1811        instance = _maybe_copy(self, copy)
1812        return Subquery(
1813            this=instance,
1814            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1815        )
1816
1817    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1818        raise NotImplementedError
1819
1820    @property
1821    def ctes(self):
1822        with_ = self.args.get("with")
1823        if not with_:
1824            return []
1825        return with_.expressions
1826
1827    @property
1828    def selects(self):
1829        raise NotImplementedError("Subqueryable objects must implement `selects`")
1830
1831    @property
1832    def named_selects(self):
1833        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
1834
1835    def with_(
1836        self,
1837        alias,
1838        as_,
1839        recursive=None,
1840        append=True,
1841        dialect=None,
1842        copy=True,
1843        **opts,
1844    ):
1845        """
1846        Append to or set the common table expressions.
1847
1848        Example:
1849            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1850            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1851
1852        Args:
1853            alias (str | Expression): the SQL code string to parse as the table name.
1854                If an `Expression` instance is passed, this is used as-is.
1855            as_ (str | Expression): the SQL code string to parse as the table expression.
1856                If an `Expression` instance is passed, it will be used as-is.
1857            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1858            append (bool): if `True`, add to any existing expressions.
1859                Otherwise, this resets the expressions.
1860            dialect (str): the dialect used to parse the input expression.
1861            copy (bool): if `False`, modify this expression instance in-place.
1862            opts (kwargs): other options to use to parse the input expressions.
1863
1864        Returns:
1865            Select: the modified expression.
1866        """
1867        alias_expression = maybe_parse(
1868            alias,
1869            dialect=dialect,
1870            into=TableAlias,
1871            **opts,
1872        )
1873        as_expression = maybe_parse(
1874            as_,
1875            dialect=dialect,
1876            **opts,
1877        )
1878        cte = CTE(
1879            this=as_expression,
1880            alias=alias_expression,
1881        )
1882        return _apply_child_list_builder(
1883            cte,
1884            instance=self,
1885            arg="with",
1886            append=append,
1887            copy=copy,
1888            into=With,
1889            properties={"recursive": recursive or False},
1890        )
def subquery(self, alias=None, copy=True) -> sqlglot.expressions.Subquery:
1795    def subquery(self, alias=None, copy=True) -> Subquery:
1796        """
1797        Convert this expression to an aliased expression that can be used as a Subquery.
1798
1799        Example:
1800            >>> subquery = Select().select("x").from_("tbl").subquery()
1801            >>> Select().select("x").from_(subquery).sql()
1802            'SELECT x FROM (SELECT x FROM tbl)'
1803
1804        Args:
1805            alias (str | Identifier): an optional alias for the subquery
1806            copy (bool): if `False`, modify this expression instance in-place.
1807
1808        Returns:
1809            Alias: the subquery
1810        """
1811        instance = _maybe_copy(self, copy)
1812        return Subquery(
1813            this=instance,
1814            alias=TableAlias(this=to_identifier(alias)) if alias else None,
1815        )

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1817    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1818        raise NotImplementedError
def with_( self, alias, as_, recursive=None, append=True, dialect=None, copy=True, **opts):
1835    def with_(
1836        self,
1837        alias,
1838        as_,
1839        recursive=None,
1840        append=True,
1841        dialect=None,
1842        copy=True,
1843        **opts,
1844    ):
1845        """
1846        Append to or set the common table expressions.
1847
1848        Example:
1849            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
1850            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
1851
1852        Args:
1853            alias (str | Expression): the SQL code string to parse as the table name.
1854                If an `Expression` instance is passed, this is used as-is.
1855            as_ (str | Expression): the SQL code string to parse as the table expression.
1856                If an `Expression` instance is passed, it will be used as-is.
1857            recursive (bool): set the RECURSIVE part of the expression. Defaults to `False`.
1858            append (bool): if `True`, add to any existing expressions.
1859                Otherwise, this resets the expressions.
1860            dialect (str): the dialect used to parse the input expression.
1861            copy (bool): if `False`, modify this expression instance in-place.
1862            opts (kwargs): other options to use to parse the input expressions.
1863
1864        Returns:
1865            Select: the modified expression.
1866        """
1867        alias_expression = maybe_parse(
1868            alias,
1869            dialect=dialect,
1870            into=TableAlias,
1871            **opts,
1872        )
1873        as_expression = maybe_parse(
1874            as_,
1875            dialect=dialect,
1876            **opts,
1877        )
1878        cte = CTE(
1879            this=as_expression,
1880            alias=alias_expression,
1881        )
1882        return _apply_child_list_builder(
1883            cte,
1884            instance=self,
1885            arg="with",
1886            append=append,
1887            copy=copy,
1888            into=With,
1889            properties={"recursive": recursive or False},
1890        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias (str | Expression): the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_ (str | Expression): the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive (bool): set the RECURSIVE part of the expression. Defaults to False.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

class Table(Expression):
1914class Table(Expression):
1915    arg_types = {
1916        "this": True,
1917        "alias": False,
1918        "db": False,
1919        "catalog": False,
1920        "laterals": False,
1921        "joins": False,
1922        "pivots": False,
1923        "hints": False,
1924        "system_time": False,
1925    }
1926
1927    @property
1928    def db(self) -> str:
1929        return self.text("db")
1930
1931    @property
1932    def catalog(self) -> str:
1933        return self.text("catalog")
class SystemTime(Expression):
1937class SystemTime(Expression):
1938    arg_types = {
1939        "this": False,
1940        "expression": False,
1941        "kind": True,
1942    }
class Union(Subqueryable):
1945class Union(Subqueryable):
1946    arg_types = {
1947        "with": False,
1948        "this": True,
1949        "expression": True,
1950        "distinct": False,
1951        **QUERY_MODIFIERS,
1952    }
1953
1954    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1955        """
1956        Set the LIMIT expression.
1957
1958        Example:
1959            >>> select("1").union(select("1")).limit(1).sql()
1960            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1961
1962        Args:
1963            expression (str | int | Expression): the SQL code string to parse.
1964                This can also be an integer.
1965                If a `Limit` instance is passed, this is used as-is.
1966                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1967            dialect (str): the dialect used to parse the input expression.
1968            copy (bool): if `False`, modify this expression instance in-place.
1969            opts (kwargs): other options to use to parse the input expressions.
1970
1971        Returns:
1972            Select: The limited subqueryable.
1973        """
1974        return (
1975            select("*")
1976            .from_(self.subquery(alias="_l_0", copy=copy))
1977            .limit(expression, dialect=dialect, copy=False, **opts)
1978        )
1979
1980    def select(
1981        self,
1982        *expressions: ExpOrStr,
1983        append: bool = True,
1984        dialect: DialectType = None,
1985        copy: bool = True,
1986        **opts,
1987    ) -> Union:
1988        """Append to or set the SELECT of the union recursively.
1989
1990        Example:
1991            >>> from sqlglot import parse_one
1992            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1993            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1994
1995        Args:
1996            *expressions: the SQL code strings to parse.
1997                If an `Expression` instance is passed, it will be used as-is.
1998            append: if `True`, add to any existing expressions.
1999                Otherwise, this resets the expressions.
2000            dialect: the dialect used to parse the input expressions.
2001            copy: if `False`, modify this expression instance in-place.
2002            opts: other options to use to parse the input expressions.
2003
2004        Returns:
2005            Union: the modified expression.
2006        """
2007        this = self.copy() if copy else self
2008        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2009        this.expression.unnest().select(
2010            *expressions, append=append, dialect=dialect, copy=False, **opts
2011        )
2012        return this
2013
2014    @property
2015    def named_selects(self):
2016        return self.this.unnest().named_selects
2017
2018    @property
2019    def is_star(self) -> bool:
2020        return self.this.is_star or self.expression.is_star
2021
2022    @property
2023    def selects(self):
2024        return self.this.unnest().selects
2025
2026    @property
2027    def left(self):
2028        return self.this
2029
2030    @property
2031    def right(self):
2032        return self.expression
def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
1954    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
1955        """
1956        Set the LIMIT expression.
1957
1958        Example:
1959            >>> select("1").union(select("1")).limit(1).sql()
1960            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
1961
1962        Args:
1963            expression (str | int | Expression): the SQL code string to parse.
1964                This can also be an integer.
1965                If a `Limit` instance is passed, this is used as-is.
1966                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
1967            dialect (str): the dialect used to parse the input expression.
1968            copy (bool): if `False`, modify this expression instance in-place.
1969            opts (kwargs): other options to use to parse the input expressions.
1970
1971        Returns:
1972            Select: The limited subqueryable.
1973        """
1974        return (
1975            select("*")
1976            .from_(self.subquery(alias="_l_0", copy=copy))
1977            .limit(expression, dialect=dialect, copy=False, **opts)
1978        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
1980    def select(
1981        self,
1982        *expressions: ExpOrStr,
1983        append: bool = True,
1984        dialect: DialectType = None,
1985        copy: bool = True,
1986        **opts,
1987    ) -> Union:
1988        """Append to or set the SELECT of the union recursively.
1989
1990        Example:
1991            >>> from sqlglot import parse_one
1992            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
1993            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
1994
1995        Args:
1996            *expressions: the SQL code strings to parse.
1997                If an `Expression` instance is passed, it will be used as-is.
1998            append: if `True`, add to any existing expressions.
1999                Otherwise, this resets the expressions.
2000            dialect: the dialect used to parse the input expressions.
2001            copy: if `False`, modify this expression instance in-place.
2002            opts: other options to use to parse the input expressions.
2003
2004        Returns:
2005            Union: the modified expression.
2006        """
2007        this = self.copy() if copy else self
2008        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2009        this.expression.unnest().select(
2010            *expressions, append=append, dialect=dialect, copy=False, **opts
2011        )
2012        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

is_star: bool

Checks whether an expression is a star.

class Except(Union):
2035class Except(Union):
2036    pass
class Intersect(Union):
2039class Intersect(Union):
2040    pass
class Unnest(UDTF):
2043class Unnest(UDTF):
2044    arg_types = {
2045        "expressions": True,
2046        "ordinality": False,
2047        "alias": False,
2048        "offset": False,
2049    }
class Update(Expression):
2052class Update(Expression):
2053    arg_types = {
2054        "with": False,
2055        "this": False,
2056        "expressions": True,
2057        "from": False,
2058        "where": False,
2059        "returning": False,
2060    }
class Values(UDTF):
2063class Values(UDTF):
2064    arg_types = {
2065        "expressions": True,
2066        "ordinality": False,
2067        "alias": False,
2068    }
class Var(Expression):
2071class Var(Expression):
2072    pass
class Schema(Expression):
2075class Schema(Expression):
2076    arg_types = {"this": False, "expressions": False}
class Lock(Expression):
2081class Lock(Expression):
2082    arg_types = {"update": True}
class Select(Subqueryable):
2085class Select(Subqueryable):
2086    arg_types = {
2087        "with": False,
2088        "kind": False,
2089        "expressions": False,
2090        "hint": False,
2091        "distinct": False,
2092        "into": False,
2093        "from": False,
2094        **QUERY_MODIFIERS,
2095    }
2096
2097    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2098        """
2099        Set the FROM expression.
2100
2101        Example:
2102            >>> Select().from_("tbl").select("x").sql()
2103            'SELECT x FROM tbl'
2104
2105        Args:
2106            *expressions (str | Expression): the SQL code strings to parse.
2107                If a `From` instance is passed, this is used as-is.
2108                If another `Expression` instance is passed, it will be wrapped in a `From`.
2109            append (bool): if `True`, add to any existing expressions.
2110                Otherwise, this flattens all the `From` expression into a single expression.
2111            dialect (str): the dialect used to parse the input expression.
2112            copy (bool): if `False`, modify this expression instance in-place.
2113            opts (kwargs): other options to use to parse the input expressions.
2114
2115        Returns:
2116            Select: the modified expression.
2117        """
2118        return _apply_child_list_builder(
2119            *expressions,
2120            instance=self,
2121            arg="from",
2122            append=append,
2123            copy=copy,
2124            prefix="FROM",
2125            into=From,
2126            dialect=dialect,
2127            **opts,
2128        )
2129
2130    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2131        """
2132        Set the GROUP BY expression.
2133
2134        Example:
2135            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2136            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2137
2138        Args:
2139            *expressions (str | Expression): the SQL code strings to parse.
2140                If a `Group` instance is passed, this is used as-is.
2141                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2142                If nothing is passed in then a group by is not applied to the expression
2143            append (bool): if `True`, add to any existing expressions.
2144                Otherwise, this flattens all the `Group` expression into a single expression.
2145            dialect (str): the dialect used to parse the input expression.
2146            copy (bool): if `False`, modify this expression instance in-place.
2147            opts (kwargs): other options to use to parse the input expressions.
2148
2149        Returns:
2150            Select: the modified expression.
2151        """
2152        if not expressions:
2153            return self if not copy else self.copy()
2154        return _apply_child_list_builder(
2155            *expressions,
2156            instance=self,
2157            arg="group",
2158            append=append,
2159            copy=copy,
2160            prefix="GROUP BY",
2161            into=Group,
2162            dialect=dialect,
2163            **opts,
2164        )
2165
2166    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2167        """
2168        Set the ORDER BY expression.
2169
2170        Example:
2171            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2172            'SELECT x FROM tbl ORDER BY x DESC'
2173
2174        Args:
2175            *expressions (str | Expression): the SQL code strings to parse.
2176                If a `Group` instance is passed, this is used as-is.
2177                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2178            append (bool): if `True`, add to any existing expressions.
2179                Otherwise, this flattens all the `Order` expression into a single expression.
2180            dialect (str): the dialect used to parse the input expression.
2181            copy (bool): if `False`, modify this expression instance in-place.
2182            opts (kwargs): other options to use to parse the input expressions.
2183
2184        Returns:
2185            Select: the modified expression.
2186        """
2187        return _apply_child_list_builder(
2188            *expressions,
2189            instance=self,
2190            arg="order",
2191            append=append,
2192            copy=copy,
2193            prefix="ORDER BY",
2194            into=Order,
2195            dialect=dialect,
2196            **opts,
2197        )
2198
2199    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2200        """
2201        Set the SORT BY expression.
2202
2203        Example:
2204            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2205            'SELECT x FROM tbl SORT BY x DESC'
2206
2207        Args:
2208            *expressions (str | Expression): the SQL code strings to parse.
2209                If a `Group` instance is passed, this is used as-is.
2210                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2211            append (bool): if `True`, add to any existing expressions.
2212                Otherwise, this flattens all the `Order` expression into a single expression.
2213            dialect (str): the dialect used to parse the input expression.
2214            copy (bool): if `False`, modify this expression instance in-place.
2215            opts (kwargs): other options to use to parse the input expressions.
2216
2217        Returns:
2218            Select: the modified expression.
2219        """
2220        return _apply_child_list_builder(
2221            *expressions,
2222            instance=self,
2223            arg="sort",
2224            append=append,
2225            copy=copy,
2226            prefix="SORT BY",
2227            into=Sort,
2228            dialect=dialect,
2229            **opts,
2230        )
2231
2232    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2233        """
2234        Set the CLUSTER BY expression.
2235
2236        Example:
2237            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2238            'SELECT x FROM tbl CLUSTER BY x DESC'
2239
2240        Args:
2241            *expressions (str | Expression): the SQL code strings to parse.
2242                If a `Group` instance is passed, this is used as-is.
2243                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2244            append (bool): if `True`, add to any existing expressions.
2245                Otherwise, this flattens all the `Order` expression into a single expression.
2246            dialect (str): the dialect used to parse the input expression.
2247            copy (bool): if `False`, modify this expression instance in-place.
2248            opts (kwargs): other options to use to parse the input expressions.
2249
2250        Returns:
2251            Select: the modified expression.
2252        """
2253        return _apply_child_list_builder(
2254            *expressions,
2255            instance=self,
2256            arg="cluster",
2257            append=append,
2258            copy=copy,
2259            prefix="CLUSTER BY",
2260            into=Cluster,
2261            dialect=dialect,
2262            **opts,
2263        )
2264
2265    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2266        """
2267        Set the LIMIT expression.
2268
2269        Example:
2270            >>> Select().from_("tbl").select("x").limit(10).sql()
2271            'SELECT x FROM tbl LIMIT 10'
2272
2273        Args:
2274            expression (str | int | Expression): the SQL code string to parse.
2275                This can also be an integer.
2276                If a `Limit` instance is passed, this is used as-is.
2277                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2278            dialect (str): the dialect used to parse the input expression.
2279            copy (bool): if `False`, modify this expression instance in-place.
2280            opts (kwargs): other options to use to parse the input expressions.
2281
2282        Returns:
2283            Select: the modified expression.
2284        """
2285        return _apply_builder(
2286            expression=expression,
2287            instance=self,
2288            arg="limit",
2289            into=Limit,
2290            prefix="LIMIT",
2291            dialect=dialect,
2292            copy=copy,
2293            **opts,
2294        )
2295
2296    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2297        """
2298        Set the OFFSET expression.
2299
2300        Example:
2301            >>> Select().from_("tbl").select("x").offset(10).sql()
2302            'SELECT x FROM tbl OFFSET 10'
2303
2304        Args:
2305            expression (str | int | Expression): the SQL code string to parse.
2306                This can also be an integer.
2307                If a `Offset` instance is passed, this is used as-is.
2308                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2309            dialect (str): the dialect used to parse the input expression.
2310            copy (bool): if `False`, modify this expression instance in-place.
2311            opts (kwargs): other options to use to parse the input expressions.
2312
2313        Returns:
2314            Select: the modified expression.
2315        """
2316        return _apply_builder(
2317            expression=expression,
2318            instance=self,
2319            arg="offset",
2320            into=Offset,
2321            prefix="OFFSET",
2322            dialect=dialect,
2323            copy=copy,
2324            **opts,
2325        )
2326
2327    def select(
2328        self,
2329        *expressions: ExpOrStr,
2330        append: bool = True,
2331        dialect: DialectType = None,
2332        copy: bool = True,
2333        **opts,
2334    ) -> Select:
2335        """
2336        Append to or set the SELECT expressions.
2337
2338        Example:
2339            >>> Select().select("x", "y").sql()
2340            'SELECT x, y'
2341
2342        Args:
2343            *expressions: the SQL code strings to parse.
2344                If an `Expression` instance is passed, it will be used as-is.
2345            append: if `True`, add to any existing expressions.
2346                Otherwise, this resets the expressions.
2347            dialect: the dialect used to parse the input expressions.
2348            copy: if `False`, modify this expression instance in-place.
2349            opts: other options to use to parse the input expressions.
2350
2351        Returns:
2352            Select: the modified expression.
2353        """
2354        return _apply_list_builder(
2355            *expressions,
2356            instance=self,
2357            arg="expressions",
2358            append=append,
2359            dialect=dialect,
2360            copy=copy,
2361            **opts,
2362        )
2363
2364    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2365        """
2366        Append to or set the LATERAL expressions.
2367
2368        Example:
2369            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2370            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2371
2372        Args:
2373            *expressions (str | Expression): the SQL code strings to parse.
2374                If an `Expression` instance is passed, it will be used as-is.
2375            append (bool): if `True`, add to any existing expressions.
2376                Otherwise, this resets the expressions.
2377            dialect (str): the dialect used to parse the input expressions.
2378            copy (bool): if `False`, modify this expression instance in-place.
2379            opts (kwargs): other options to use to parse the input expressions.
2380
2381        Returns:
2382            Select: the modified expression.
2383        """
2384        return _apply_list_builder(
2385            *expressions,
2386            instance=self,
2387            arg="laterals",
2388            append=append,
2389            into=Lateral,
2390            prefix="LATERAL VIEW",
2391            dialect=dialect,
2392            copy=copy,
2393            **opts,
2394        )
2395
2396    def join(
2397        self,
2398        expression,
2399        on=None,
2400        using=None,
2401        append=True,
2402        join_type=None,
2403        join_alias=None,
2404        dialect=None,
2405        copy=True,
2406        **opts,
2407    ) -> Select:
2408        """
2409        Append to or set the JOIN expressions.
2410
2411        Example:
2412            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2413            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2414
2415            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2416            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2417
2418            Use `join_type` to change the type of join:
2419
2420            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2421            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2422
2423        Args:
2424            expression (str | Expression): the SQL code string to parse.
2425                If an `Expression` instance is passed, it will be used as-is.
2426            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2427                If an `Expression` instance is passed, it will be used as-is.
2428            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2429                If an `Expression` instance is passed, it will be used as-is.
2430            append (bool): if `True`, add to any existing expressions.
2431                Otherwise, this resets the expressions.
2432            join_type (str): If set, alter the parsed join type
2433            dialect (str): the dialect used to parse the input expressions.
2434            copy (bool): if `False`, modify this expression instance in-place.
2435            opts (kwargs): other options to use to parse the input expressions.
2436
2437        Returns:
2438            Select: the modified expression.
2439        """
2440        parse_args = {"dialect": dialect, **opts}
2441
2442        try:
2443            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2444        except ParseError:
2445            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2446
2447        join = expression if isinstance(expression, Join) else Join(this=expression)
2448
2449        if isinstance(join.this, Select):
2450            join.this.replace(join.this.subquery())
2451
2452        if join_type:
2453            natural: t.Optional[Token]
2454            side: t.Optional[Token]
2455            kind: t.Optional[Token]
2456
2457            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2458
2459            if natural:
2460                join.set("natural", True)
2461            if side:
2462                join.set("side", side.text)
2463            if kind:
2464                join.set("kind", kind.text)
2465
2466        if on:
2467            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2468            join.set("on", on)
2469
2470        if using:
2471            join = _apply_list_builder(
2472                *ensure_collection(using),
2473                instance=join,
2474                arg="using",
2475                append=append,
2476                copy=copy,
2477                **opts,
2478            )
2479
2480        if join_alias:
2481            join.set("this", alias_(join.this, join_alias, table=True))
2482        return _apply_list_builder(
2483            join,
2484            instance=self,
2485            arg="joins",
2486            append=append,
2487            copy=copy,
2488            **opts,
2489        )
2490
2491    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2492        """
2493        Append to or set the WHERE expressions.
2494
2495        Example:
2496            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2497            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2498
2499        Args:
2500            *expressions (str | Expression): the SQL code strings to parse.
2501                If an `Expression` instance is passed, it will be used as-is.
2502                Multiple expressions are combined with an AND operator.
2503            append (bool): if `True`, AND the new expressions to any existing expression.
2504                Otherwise, this resets the expression.
2505            dialect (str): the dialect used to parse the input expressions.
2506            copy (bool): if `False`, modify this expression instance in-place.
2507            opts (kwargs): other options to use to parse the input expressions.
2508
2509        Returns:
2510            Select: the modified expression.
2511        """
2512        return _apply_conjunction_builder(
2513            *expressions,
2514            instance=self,
2515            arg="where",
2516            append=append,
2517            into=Where,
2518            dialect=dialect,
2519            copy=copy,
2520            **opts,
2521        )
2522
2523    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2524        """
2525        Append to or set the HAVING expressions.
2526
2527        Example:
2528            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2529            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2530
2531        Args:
2532            *expressions (str | Expression): the SQL code strings to parse.
2533                If an `Expression` instance is passed, it will be used as-is.
2534                Multiple expressions are combined with an AND operator.
2535            append (bool): if `True`, AND the new expressions to any existing expression.
2536                Otherwise, this resets the expression.
2537            dialect (str): the dialect used to parse the input expressions.
2538            copy (bool): if `False`, modify this expression instance in-place.
2539            opts (kwargs): other options to use to parse the input expressions.
2540
2541        Returns:
2542            Select: the modified expression.
2543        """
2544        return _apply_conjunction_builder(
2545            *expressions,
2546            instance=self,
2547            arg="having",
2548            append=append,
2549            into=Having,
2550            dialect=dialect,
2551            copy=copy,
2552            **opts,
2553        )
2554
2555    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2556        return _apply_list_builder(
2557            *expressions,
2558            instance=self,
2559            arg="windows",
2560            append=append,
2561            into=Window,
2562            dialect=dialect,
2563            copy=copy,
2564            **opts,
2565        )
2566
2567    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2568        return _apply_conjunction_builder(
2569            *expressions,
2570            instance=self,
2571            arg="qualify",
2572            append=append,
2573            into=Qualify,
2574            dialect=dialect,
2575            copy=copy,
2576            **opts,
2577        )
2578
2579    def distinct(self, distinct=True, copy=True) -> Select:
2580        """
2581        Set the OFFSET expression.
2582
2583        Example:
2584            >>> Select().from_("tbl").select("x").distinct().sql()
2585            'SELECT DISTINCT x FROM tbl'
2586
2587        Args:
2588            distinct (bool): whether the Select should be distinct
2589            copy (bool): if `False`, modify this expression instance in-place.
2590
2591        Returns:
2592            Select: the modified expression.
2593        """
2594        instance = _maybe_copy(self, copy)
2595        instance.set("distinct", Distinct() if distinct else None)
2596        return instance
2597
2598    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2599        """
2600        Convert this expression to a CREATE TABLE AS statement.
2601
2602        Example:
2603            >>> Select().select("*").from_("tbl").ctas("x").sql()
2604            'CREATE TABLE x AS SELECT * FROM tbl'
2605
2606        Args:
2607            table (str | Expression): the SQL code string to parse as the table name.
2608                If another `Expression` instance is passed, it will be used as-is.
2609            properties (dict): an optional mapping of table properties
2610            dialect (str): the dialect used to parse the input table.
2611            copy (bool): if `False`, modify this expression instance in-place.
2612            opts (kwargs): other options to use to parse the input table.
2613
2614        Returns:
2615            Create: the CREATE TABLE AS expression
2616        """
2617        instance = _maybe_copy(self, copy)
2618        table_expression = maybe_parse(
2619            table,
2620            into=Table,
2621            dialect=dialect,
2622            **opts,
2623        )
2624        properties_expression = None
2625        if properties:
2626            properties_expression = Properties.from_dict(properties)
2627
2628        return Create(
2629            this=table_expression,
2630            kind="table",
2631            expression=instance,
2632            properties=properties_expression,
2633        )
2634
2635    def lock(self, update: bool = True, copy: bool = True) -> Select:
2636        """
2637        Set the locking read mode for this expression.
2638
2639        Examples:
2640            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2641            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2642
2643            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2644            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2645
2646        Args:
2647            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2648            copy: if `False`, modify this expression instance in-place.
2649
2650        Returns:
2651            The modified expression.
2652        """
2653
2654        inst = _maybe_copy(self, copy)
2655        inst.set("lock", Lock(update=update))
2656
2657        return inst
2658
2659    @property
2660    def named_selects(self) -> t.List[str]:
2661        return [e.output_name for e in self.expressions if e.alias_or_name]
2662
2663    @property
2664    def is_star(self) -> bool:
2665        return any(expression.is_star for expression in self.expressions)
2666
2667    @property
2668    def selects(self) -> t.List[Expression]:
2669        return self.expressions
def from_( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2097    def from_(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2098        """
2099        Set the FROM expression.
2100
2101        Example:
2102            >>> Select().from_("tbl").select("x").sql()
2103            'SELECT x FROM tbl'
2104
2105        Args:
2106            *expressions (str | Expression): the SQL code strings to parse.
2107                If a `From` instance is passed, this is used as-is.
2108                If another `Expression` instance is passed, it will be wrapped in a `From`.
2109            append (bool): if `True`, add to any existing expressions.
2110                Otherwise, this flattens all the `From` expression into a single expression.
2111            dialect (str): the dialect used to parse the input expression.
2112            copy (bool): if `False`, modify this expression instance in-place.
2113            opts (kwargs): other options to use to parse the input expressions.
2114
2115        Returns:
2116            Select: the modified expression.
2117        """
2118        return _apply_child_list_builder(
2119            *expressions,
2120            instance=self,
2121            arg="from",
2122            append=append,
2123            copy=copy,
2124            prefix="FROM",
2125            into=From,
2126            dialect=dialect,
2127            **opts,
2128        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the From expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def group_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2130    def group_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2131        """
2132        Set the GROUP BY expression.
2133
2134        Example:
2135            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2136            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2137
2138        Args:
2139            *expressions (str | Expression): the SQL code strings to parse.
2140                If a `Group` instance is passed, this is used as-is.
2141                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2142                If nothing is passed in then a group by is not applied to the expression
2143            append (bool): if `True`, add to any existing expressions.
2144                Otherwise, this flattens all the `Group` expression into a single expression.
2145            dialect (str): the dialect used to parse the input expression.
2146            copy (bool): if `False`, modify this expression instance in-place.
2147            opts (kwargs): other options to use to parse the input expressions.
2148
2149        Returns:
2150            Select: the modified expression.
2151        """
2152        if not expressions:
2153            return self if not copy else self.copy()
2154        return _apply_child_list_builder(
2155            *expressions,
2156            instance=self,
2157            arg="group",
2158            append=append,
2159            copy=copy,
2160            prefix="GROUP BY",
2161            into=Group,
2162            dialect=dialect,
2163            **opts,
2164        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def order_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2166    def order_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2167        """
2168        Set the ORDER BY expression.
2169
2170        Example:
2171            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2172            'SELECT x FROM tbl ORDER BY x DESC'
2173
2174        Args:
2175            *expressions (str | Expression): the SQL code strings to parse.
2176                If a `Group` instance is passed, this is used as-is.
2177                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2178            append (bool): if `True`, add to any existing expressions.
2179                Otherwise, this flattens all the `Order` expression into a single expression.
2180            dialect (str): the dialect used to parse the input expression.
2181            copy (bool): if `False`, modify this expression instance in-place.
2182            opts (kwargs): other options to use to parse the input expressions.
2183
2184        Returns:
2185            Select: the modified expression.
2186        """
2187        return _apply_child_list_builder(
2188            *expressions,
2189            instance=self,
2190            arg="order",
2191            append=append,
2192            copy=copy,
2193            prefix="ORDER BY",
2194            into=Order,
2195            dialect=dialect,
2196            **opts,
2197        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def sort_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2199    def sort_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2200        """
2201        Set the SORT BY expression.
2202
2203        Example:
2204            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
2205            'SELECT x FROM tbl SORT BY x DESC'
2206
2207        Args:
2208            *expressions (str | Expression): the SQL code strings to parse.
2209                If a `Group` instance is passed, this is used as-is.
2210                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2211            append (bool): if `True`, add to any existing expressions.
2212                Otherwise, this flattens all the `Order` expression into a single expression.
2213            dialect (str): the dialect used to parse the input expression.
2214            copy (bool): if `False`, modify this expression instance in-place.
2215            opts (kwargs): other options to use to parse the input expressions.
2216
2217        Returns:
2218            Select: the modified expression.
2219        """
2220        return _apply_child_list_builder(
2221            *expressions,
2222            instance=self,
2223            arg="sort",
2224            append=append,
2225            copy=copy,
2226            prefix="SORT BY",
2227            into=Sort,
2228            dialect=dialect,
2229            **opts,
2230        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql()
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def cluster_by( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2232    def cluster_by(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2233        """
2234        Set the CLUSTER BY expression.
2235
2236        Example:
2237            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
2238            'SELECT x FROM tbl CLUSTER BY x DESC'
2239
2240        Args:
2241            *expressions (str | Expression): the SQL code strings to parse.
2242                If a `Group` instance is passed, this is used as-is.
2243                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2244            append (bool): if `True`, add to any existing expressions.
2245                Otherwise, this flattens all the `Order` expression into a single expression.
2246            dialect (str): the dialect used to parse the input expression.
2247            copy (bool): if `False`, modify this expression instance in-place.
2248            opts (kwargs): other options to use to parse the input expressions.
2249
2250        Returns:
2251            Select: the modified expression.
2252        """
2253        return _apply_child_list_builder(
2254            *expressions,
2255            instance=self,
2256            arg="cluster",
2257            append=append,
2258            copy=copy,
2259            prefix="CLUSTER BY",
2260            into=Cluster,
2261            dialect=dialect,
2262            **opts,
2263        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql()
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append (bool): if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def limit( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2265    def limit(self, expression, dialect=None, copy=True, **opts) -> Select:
2266        """
2267        Set the LIMIT expression.
2268
2269        Example:
2270            >>> Select().from_("tbl").select("x").limit(10).sql()
2271            'SELECT x FROM tbl LIMIT 10'
2272
2273        Args:
2274            expression (str | int | Expression): the SQL code string to parse.
2275                This can also be an integer.
2276                If a `Limit` instance is passed, this is used as-is.
2277                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2278            dialect (str): the dialect used to parse the input expression.
2279            copy (bool): if `False`, modify this expression instance in-place.
2280            opts (kwargs): other options to use to parse the input expressions.
2281
2282        Returns:
2283            Select: the modified expression.
2284        """
2285        return _apply_builder(
2286            expression=expression,
2287            instance=self,
2288            arg="limit",
2289            into=Limit,
2290            prefix="LIMIT",
2291            dialect=dialect,
2292            copy=copy,
2293            **opts,
2294        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2296    def offset(self, expression, dialect=None, copy=True, **opts) -> Select:
2297        """
2298        Set the OFFSET expression.
2299
2300        Example:
2301            >>> Select().from_("tbl").select("x").offset(10).sql()
2302            'SELECT x FROM tbl OFFSET 10'
2303
2304        Args:
2305            expression (str | int | Expression): the SQL code string to parse.
2306                This can also be an integer.
2307                If a `Offset` instance is passed, this is used as-is.
2308                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2309            dialect (str): the dialect used to parse the input expression.
2310            copy (bool): if `False`, modify this expression instance in-place.
2311            opts (kwargs): other options to use to parse the input expressions.
2312
2313        Returns:
2314            Select: the modified expression.
2315        """
2316        return _apply_builder(
2317            expression=expression,
2318            instance=self,
2319            arg="offset",
2320            into=Offset,
2321            prefix="OFFSET",
2322            dialect=dialect,
2323            copy=copy,
2324            **opts,
2325        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression (str | int | Expression): the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect (str): the dialect used to parse the input expression.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2327    def select(
2328        self,
2329        *expressions: ExpOrStr,
2330        append: bool = True,
2331        dialect: DialectType = None,
2332        copy: bool = True,
2333        **opts,
2334    ) -> Select:
2335        """
2336        Append to or set the SELECT expressions.
2337
2338        Example:
2339            >>> Select().select("x", "y").sql()
2340            'SELECT x, y'
2341
2342        Args:
2343            *expressions: the SQL code strings to parse.
2344                If an `Expression` instance is passed, it will be used as-is.
2345            append: if `True`, add to any existing expressions.
2346                Otherwise, this resets the expressions.
2347            dialect: the dialect used to parse the input expressions.
2348            copy: if `False`, modify this expression instance in-place.
2349            opts: other options to use to parse the input expressions.
2350
2351        Returns:
2352            Select: the modified expression.
2353        """
2354        return _apply_list_builder(
2355            *expressions,
2356            instance=self,
2357            arg="expressions",
2358            append=append,
2359            dialect=dialect,
2360            copy=copy,
2361            **opts,
2362        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def lateral( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2364    def lateral(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2365        """
2366        Append to or set the LATERAL expressions.
2367
2368        Example:
2369            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2370            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2371
2372        Args:
2373            *expressions (str | Expression): the SQL code strings to parse.
2374                If an `Expression` instance is passed, it will be used as-is.
2375            append (bool): if `True`, add to any existing expressions.
2376                Otherwise, this resets the expressions.
2377            dialect (str): the dialect used to parse the input expressions.
2378            copy (bool): if `False`, modify this expression instance in-place.
2379            opts (kwargs): other options to use to parse the input expressions.
2380
2381        Returns:
2382            Select: the modified expression.
2383        """
2384        return _apply_list_builder(
2385            *expressions,
2386            instance=self,
2387            arg="laterals",
2388            append=append,
2389            into=Lateral,
2390            prefix="LATERAL VIEW",
2391            dialect=dialect,
2392            copy=copy,
2393            **opts,
2394        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def join( self, expression, on=None, using=None, append=True, join_type=None, join_alias=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2396    def join(
2397        self,
2398        expression,
2399        on=None,
2400        using=None,
2401        append=True,
2402        join_type=None,
2403        join_alias=None,
2404        dialect=None,
2405        copy=True,
2406        **opts,
2407    ) -> Select:
2408        """
2409        Append to or set the JOIN expressions.
2410
2411        Example:
2412            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2413            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2414
2415            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2416            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2417
2418            Use `join_type` to change the type of join:
2419
2420            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2421            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2422
2423        Args:
2424            expression (str | Expression): the SQL code string to parse.
2425                If an `Expression` instance is passed, it will be used as-is.
2426            on (str | Expression): optionally specify the join "on" criteria as a SQL string.
2427                If an `Expression` instance is passed, it will be used as-is.
2428            using (str | Expression): optionally specify the join "using" criteria as a SQL string.
2429                If an `Expression` instance is passed, it will be used as-is.
2430            append (bool): if `True`, add to any existing expressions.
2431                Otherwise, this resets the expressions.
2432            join_type (str): If set, alter the parsed join type
2433            dialect (str): the dialect used to parse the input expressions.
2434            copy (bool): if `False`, modify this expression instance in-place.
2435            opts (kwargs): other options to use to parse the input expressions.
2436
2437        Returns:
2438            Select: the modified expression.
2439        """
2440        parse_args = {"dialect": dialect, **opts}
2441
2442        try:
2443            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2444        except ParseError:
2445            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2446
2447        join = expression if isinstance(expression, Join) else Join(this=expression)
2448
2449        if isinstance(join.this, Select):
2450            join.this.replace(join.this.subquery())
2451
2452        if join_type:
2453            natural: t.Optional[Token]
2454            side: t.Optional[Token]
2455            kind: t.Optional[Token]
2456
2457            natural, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2458
2459            if natural:
2460                join.set("natural", True)
2461            if side:
2462                join.set("side", side.text)
2463            if kind:
2464                join.set("kind", kind.text)
2465
2466        if on:
2467            on = and_(*ensure_collection(on), dialect=dialect, **opts)
2468            join.set("on", on)
2469
2470        if using:
2471            join = _apply_list_builder(
2472                *ensure_collection(using),
2473                instance=join,
2474                arg="using",
2475                append=append,
2476                copy=copy,
2477                **opts,
2478            )
2479
2480        if join_alias:
2481            join.set("this", alias_(join.this, join_alias, table=True))
2482        return _apply_list_builder(
2483            join,
2484            instance=self,
2485            arg="joins",
2486            append=append,
2487            copy=copy,
2488            **opts,
2489        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on (str | Expression): optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using (str | Expression): optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append (bool): if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type (str): If set, alter the parsed join type
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2491    def where(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2492        """
2493        Append to or set the WHERE expressions.
2494
2495        Example:
2496            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2497            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2498
2499        Args:
2500            *expressions (str | Expression): the SQL code strings to parse.
2501                If an `Expression` instance is passed, it will be used as-is.
2502                Multiple expressions are combined with an AND operator.
2503            append (bool): if `True`, AND the new expressions to any existing expression.
2504                Otherwise, this resets the expression.
2505            dialect (str): the dialect used to parse the input expressions.
2506            copy (bool): if `False`, modify this expression instance in-place.
2507            opts (kwargs): other options to use to parse the input expressions.
2508
2509        Returns:
2510            Select: the modified expression.
2511        """
2512        return _apply_conjunction_builder(
2513            *expressions,
2514            instance=self,
2515            arg="where",
2516            append=append,
2517            into=Where,
2518            dialect=dialect,
2519            copy=copy,
2520            **opts,
2521        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2523    def having(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2524        """
2525        Append to or set the HAVING expressions.
2526
2527        Example:
2528            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2529            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2530
2531        Args:
2532            *expressions (str | Expression): the SQL code strings to parse.
2533                If an `Expression` instance is passed, it will be used as-is.
2534                Multiple expressions are combined with an AND operator.
2535            append (bool): if `True`, AND the new expressions to any existing expression.
2536                Otherwise, this resets the expression.
2537            dialect (str): the dialect used to parse the input expressions.
2538            copy (bool): if `False`, modify this expression instance in-place.
2539            opts (kwargs): other options to use to parse the input expressions.
2540
2541        Returns:
2542            Select: the modified expression.
2543        """
2544        return _apply_conjunction_builder(
2545            *expressions,
2546            instance=self,
2547            arg="having",
2548            append=append,
2549            into=Having,
2550            dialect=dialect,
2551            copy=copy,
2552            **opts,
2553        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append (bool): if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect (str): the dialect used to parse the input expressions.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def window( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2555    def window(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2556        return _apply_list_builder(
2557            *expressions,
2558            instance=self,
2559            arg="windows",
2560            append=append,
2561            into=Window,
2562            dialect=dialect,
2563            copy=copy,
2564            **opts,
2565        )
def qualify( self, *expressions, append=True, dialect=None, copy=True, **opts) -> sqlglot.expressions.Select:
2567    def qualify(self, *expressions, append=True, dialect=None, copy=True, **opts) -> Select:
2568        return _apply_conjunction_builder(
2569            *expressions,
2570            instance=self,
2571            arg="qualify",
2572            append=append,
2573            into=Qualify,
2574            dialect=dialect,
2575            copy=copy,
2576            **opts,
2577        )
def distinct(self, distinct=True, copy=True) -> sqlglot.expressions.Select:
2579    def distinct(self, distinct=True, copy=True) -> Select:
2580        """
2581        Set the OFFSET expression.
2582
2583        Example:
2584            >>> Select().from_("tbl").select("x").distinct().sql()
2585            'SELECT DISTINCT x FROM tbl'
2586
2587        Args:
2588            distinct (bool): whether the Select should be distinct
2589            copy (bool): if `False`, modify this expression instance in-place.
2590
2591        Returns:
2592            Select: the modified expression.
2593        """
2594        instance = _maybe_copy(self, copy)
2595        instance.set("distinct", Distinct() if distinct else None)
2596        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • distinct (bool): whether the Select should be distinct
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table, properties=None, dialect=None, copy=True, **opts) -> sqlglot.expressions.Create:
2598    def ctas(self, table, properties=None, dialect=None, copy=True, **opts) -> Create:
2599        """
2600        Convert this expression to a CREATE TABLE AS statement.
2601
2602        Example:
2603            >>> Select().select("*").from_("tbl").ctas("x").sql()
2604            'CREATE TABLE x AS SELECT * FROM tbl'
2605
2606        Args:
2607            table (str | Expression): the SQL code string to parse as the table name.
2608                If another `Expression` instance is passed, it will be used as-is.
2609            properties (dict): an optional mapping of table properties
2610            dialect (str): the dialect used to parse the input table.
2611            copy (bool): if `False`, modify this expression instance in-place.
2612            opts (kwargs): other options to use to parse the input table.
2613
2614        Returns:
2615            Create: the CREATE TABLE AS expression
2616        """
2617        instance = _maybe_copy(self, copy)
2618        table_expression = maybe_parse(
2619            table,
2620            into=Table,
2621            dialect=dialect,
2622            **opts,
2623        )
2624        properties_expression = None
2625        if properties:
2626            properties_expression = Properties.from_dict(properties)
2627
2628        return Create(
2629            this=table_expression,
2630            kind="table",
2631            expression=instance,
2632            properties=properties_expression,
2633        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table (str | Expression): the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties (dict): an optional mapping of table properties
  • dialect (str): the dialect used to parse the input table.
  • copy (bool): if False, modify this expression instance in-place.
  • opts (kwargs): other options to use to parse the input table.
Returns:

Create: the CREATE TABLE AS expression

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
2635    def lock(self, update: bool = True, copy: bool = True) -> Select:
2636        """
2637        Set the locking read mode for this expression.
2638
2639        Examples:
2640            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
2641            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
2642
2643            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
2644            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
2645
2646        Args:
2647            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
2648            copy: if `False`, modify this expression instance in-place.
2649
2650        Returns:
2651            The modified expression.
2652        """
2653
2654        inst = _maybe_copy(self, copy)
2655        inst.set("lock", Lock(update=update))
2656
2657        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

is_star: bool

Checks whether an expression is a star.

class Subquery(DerivedTable, Unionable):
2672class Subquery(DerivedTable, Unionable):
2673    arg_types = {
2674        "this": True,
2675        "alias": False,
2676        "with": False,
2677        **QUERY_MODIFIERS,
2678    }
2679
2680    def unnest(self):
2681        """
2682        Returns the first non subquery.
2683        """
2684        expression = self
2685        while isinstance(expression, Subquery):
2686            expression = expression.this
2687        return expression
2688
2689    @property
2690    def is_star(self) -> bool:
2691        return self.this.is_star
2692
2693    @property
2694    def output_name(self):
2695        return self.alias
def unnest(self):
2680    def unnest(self):
2681        """
2682        Returns the first non subquery.
2683        """
2684        expression = self
2685        while isinstance(expression, Subquery):
2686            expression = expression.this
2687        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class TableSample(Expression):
2698class TableSample(Expression):
2699    arg_types = {
2700        "this": False,
2701        "method": False,
2702        "bucket_numerator": False,
2703        "bucket_denominator": False,
2704        "bucket_field": False,
2705        "percent": False,
2706        "rows": False,
2707        "size": False,
2708        "seed": False,
2709        "kind": False,
2710    }
class Tag(Expression):
2713class Tag(Expression):
2714    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
2715
2716    arg_types = {
2717        "this": False,
2718        "prefix": False,
2719        "postfix": False,
2720    }

Tags are used for generating arbitrary sql like SELECT x.

class Pivot(Expression):
2723class Pivot(Expression):
2724    arg_types = {
2725        "this": False,
2726        "alias": False,
2727        "expressions": True,
2728        "field": True,
2729        "unpivot": True,
2730    }
class Window(Expression):
2733class Window(Expression):
2734    arg_types = {
2735        "this": True,
2736        "partition_by": False,
2737        "order": False,
2738        "spec": False,
2739        "alias": False,
2740    }
class WindowSpec(Expression):
2743class WindowSpec(Expression):
2744    arg_types = {
2745        "kind": False,
2746        "start": False,
2747        "start_side": False,
2748        "end": False,
2749        "end_side": False,
2750    }
class Where(Expression):
2753class Where(Expression):
2754    pass
class Star(Expression):
2757class Star(Expression):
2758    arg_types = {"except": False, "replace": False}
2759
2760    @property
2761    def name(self) -> str:
2762        return "*"
2763
2764    @property
2765    def output_name(self):
2766        return self.name
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Parameter(Expression):
2769class Parameter(Expression):
2770    arg_types = {"this": True, "wrapped": False}
class SessionParameter(Expression):
2773class SessionParameter(Expression):
2774    arg_types = {"this": True, "kind": False}
class Placeholder(Expression):
2777class Placeholder(Expression):
2778    arg_types = {"this": False}
class Null(Condition):
2781class Null(Condition):
2782    arg_types: t.Dict[str, t.Any] = {}
2783
2784    @property
2785    def name(self) -> str:
2786        return "NULL"
class Boolean(Condition):
2789class Boolean(Condition):
2790    pass
class DataType(Expression):
2793class DataType(Expression):
2794    arg_types = {
2795        "this": True,
2796        "expressions": False,
2797        "nested": False,
2798        "values": False,
2799        "prefix": False,
2800    }
2801
2802    class Type(AutoName):
2803        CHAR = auto()
2804        NCHAR = auto()
2805        VARCHAR = auto()
2806        NVARCHAR = auto()
2807        TEXT = auto()
2808        MEDIUMTEXT = auto()
2809        LONGTEXT = auto()
2810        MEDIUMBLOB = auto()
2811        LONGBLOB = auto()
2812        BINARY = auto()
2813        VARBINARY = auto()
2814        INT = auto()
2815        UINT = auto()
2816        TINYINT = auto()
2817        UTINYINT = auto()
2818        SMALLINT = auto()
2819        USMALLINT = auto()
2820        BIGINT = auto()
2821        UBIGINT = auto()
2822        FLOAT = auto()
2823        DOUBLE = auto()
2824        DECIMAL = auto()
2825        BIT = auto()
2826        BOOLEAN = auto()
2827        JSON = auto()
2828        JSONB = auto()
2829        INTERVAL = auto()
2830        TIME = auto()
2831        TIMESTAMP = auto()
2832        TIMESTAMPTZ = auto()
2833        TIMESTAMPLTZ = auto()
2834        DATE = auto()
2835        DATETIME = auto()
2836        ARRAY = auto()
2837        MAP = auto()
2838        UUID = auto()
2839        GEOGRAPHY = auto()
2840        GEOMETRY = auto()
2841        STRUCT = auto()
2842        NULLABLE = auto()
2843        HLLSKETCH = auto()
2844        HSTORE = auto()
2845        SUPER = auto()
2846        SERIAL = auto()
2847        SMALLSERIAL = auto()
2848        BIGSERIAL = auto()
2849        XML = auto()
2850        UNIQUEIDENTIFIER = auto()
2851        MONEY = auto()
2852        SMALLMONEY = auto()
2853        ROWVERSION = auto()
2854        IMAGE = auto()
2855        VARIANT = auto()
2856        OBJECT = auto()
2857        INET = auto()
2858        NULL = auto()
2859        UNKNOWN = auto()  # Sentinel value, useful for type annotation
2860
2861    TEXT_TYPES = {
2862        Type.CHAR,
2863        Type.NCHAR,
2864        Type.VARCHAR,
2865        Type.NVARCHAR,
2866        Type.TEXT,
2867    }
2868
2869    INTEGER_TYPES = {
2870        Type.INT,
2871        Type.TINYINT,
2872        Type.SMALLINT,
2873        Type.BIGINT,
2874    }
2875
2876    FLOAT_TYPES = {
2877        Type.FLOAT,
2878        Type.DOUBLE,
2879    }
2880
2881    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
2882
2883    TEMPORAL_TYPES = {
2884        Type.TIMESTAMP,
2885        Type.TIMESTAMPTZ,
2886        Type.TIMESTAMPLTZ,
2887        Type.DATE,
2888        Type.DATETIME,
2889    }
2890
2891    @classmethod
2892    def build(
2893        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2894    ) -> DataType:
2895        from sqlglot import parse_one
2896
2897        if isinstance(dtype, str):
2898            if dtype.upper() in cls.Type.__members__:
2899                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2900            else:
2901                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2902            if data_type_exp is None:
2903                raise ValueError(f"Unparsable data type value: {dtype}")
2904        elif isinstance(dtype, DataType.Type):
2905            data_type_exp = DataType(this=dtype)
2906        elif isinstance(dtype, DataType):
2907            return dtype
2908        else:
2909            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2910        return DataType(**{**data_type_exp.args, **kwargs})
2911
2912    def is_type(self, dtype: DataType.Type) -> bool:
2913        return self.this == dtype
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
2891    @classmethod
2892    def build(
2893        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
2894    ) -> DataType:
2895        from sqlglot import parse_one
2896
2897        if isinstance(dtype, str):
2898            if dtype.upper() in cls.Type.__members__:
2899                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[dtype.upper()])
2900            else:
2901                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
2902            if data_type_exp is None:
2903                raise ValueError(f"Unparsable data type value: {dtype}")
2904        elif isinstance(dtype, DataType.Type):
2905            data_type_exp = DataType(this=dtype)
2906        elif isinstance(dtype, DataType):
2907            return dtype
2908        else:
2909            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
2910        return DataType(**{**data_type_exp.args, **kwargs})
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
2912    def is_type(self, dtype: DataType.Type) -> bool:
2913        return self.this == dtype
class DataType.Type(sqlglot.helper.AutoName):
2802    class Type(AutoName):
2803        CHAR = auto()
2804        NCHAR = auto()
2805        VARCHAR = auto()
2806        NVARCHAR = auto()
2807        TEXT = auto()
2808        MEDIUMTEXT = auto()
2809        LONGTEXT = auto()
2810        MEDIUMBLOB = auto()
2811        LONGBLOB = auto()
2812        BINARY = auto()
2813        VARBINARY = auto()
2814        INT = auto()
2815        UINT = auto()
2816        TINYINT = auto()
2817        UTINYINT = auto()
2818        SMALLINT = auto()
2819        USMALLINT = auto()
2820        BIGINT = auto()
2821        UBIGINT = auto()
2822        FLOAT = auto()
2823        DOUBLE = auto()
2824        DECIMAL = auto()
2825        BIT = auto()
2826        BOOLEAN = auto()
2827        JSON = auto()
2828        JSONB = auto()
2829        INTERVAL = auto()
2830        TIME = auto()
2831        TIMESTAMP = auto()
2832        TIMESTAMPTZ = auto()
2833        TIMESTAMPLTZ = auto()
2834        DATE = auto()
2835        DATETIME = auto()
2836        ARRAY = auto()
2837        MAP = auto()
2838        UUID = auto()
2839        GEOGRAPHY = auto()
2840        GEOMETRY = auto()
2841        STRUCT = auto()
2842        NULLABLE = auto()
2843        HLLSKETCH = auto()
2844        HSTORE = auto()
2845        SUPER = auto()
2846        SERIAL = auto()
2847        SMALLSERIAL = auto()
2848        BIGSERIAL = auto()
2849        XML = auto()
2850        UNIQUEIDENTIFIER = auto()
2851        MONEY = auto()
2852        SMALLMONEY = auto()
2853        ROWVERSION = auto()
2854        IMAGE = auto()
2855        VARIANT = auto()
2856        OBJECT = auto()
2857        INET = auto()
2858        NULL = auto()
2859        UNKNOWN = auto()  # Sentinel value, useful for type annotation

An enumeration.

CHAR = <Type.CHAR: 'CHAR'>
NCHAR = <Type.NCHAR: 'NCHAR'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
TEXT = <Type.TEXT: 'TEXT'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
BINARY = <Type.BINARY: 'BINARY'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
INT = <Type.INT: 'INT'>
UINT = <Type.UINT: 'UINT'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
BIGINT = <Type.BIGINT: 'BIGINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
FLOAT = <Type.FLOAT: 'FLOAT'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
ARRAY = <Type.ARRAY: 'ARRAY'>
MAP = <Type.MAP: 'MAP'>
UUID = <Type.UUID: 'UUID'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
STRUCT = <Type.STRUCT: 'STRUCT'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
SUPER = <Type.SUPER: 'SUPER'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
XML = <Type.XML: 'XML'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
MONEY = <Type.MONEY: 'MONEY'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
IMAGE = <Type.IMAGE: 'IMAGE'>
VARIANT = <Type.VARIANT: 'VARIANT'>
OBJECT = <Type.OBJECT: 'OBJECT'>
INET = <Type.INET: 'INET'>
NULL = <Type.NULL: 'NULL'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
2917class PseudoType(Expression):
2918    pass
class StructKwarg(Expression):
2921class StructKwarg(Expression):
2922    arg_types = {"this": True, "expression": True}
class SubqueryPredicate(Predicate):
2926class SubqueryPredicate(Predicate):
2927    pass
class All(SubqueryPredicate):
2930class All(SubqueryPredicate):
2931    pass
class Any(SubqueryPredicate):
2934class Any(SubqueryPredicate):
2935    pass
class Exists(SubqueryPredicate):
2938class Exists(SubqueryPredicate):
2939    pass
class Command(Expression):
2944class Command(Expression):
2945    arg_types = {"this": True, "expression": False}
class Transaction(Expression):
2948class Transaction(Expression):
2949    arg_types = {"this": False, "modes": False}
class Commit(Expression):
2952class Commit(Expression):
2953    arg_types = {"chain": False}
class Rollback(Expression):
2956class Rollback(Expression):
2957    arg_types = {"savepoint": False}
class AlterTable(Expression):
2960class AlterTable(Expression):
2961    arg_types = {"this": True, "actions": True, "exists": False}
class AddConstraint(Expression):
2964class AddConstraint(Expression):
2965    arg_types = {"this": False, "expression": False, "enforced": False}
class DropPartition(Expression):
2968class DropPartition(Expression):
2969    arg_types = {"expressions": True, "exists": False}
class Binary(Expression):
2973class Binary(Expression):
2974    arg_types = {"this": True, "expression": True}
2975
2976    @property
2977    def left(self):
2978        return self.this
2979
2980    @property
2981    def right(self):
2982        return self.expression
class Add(Binary):
2985class Add(Binary):
2986    pass
class Connector(Binary, Condition):
2989class Connector(Binary, Condition):
2990    pass
class And(Connector):
2993class And(Connector):
2994    pass
class Or(Connector):
2997class Or(Connector):
2998    pass
class BitwiseAnd(Binary):
3001class BitwiseAnd(Binary):
3002    pass
class BitwiseLeftShift(Binary):
3005class BitwiseLeftShift(Binary):
3006    pass
class BitwiseOr(Binary):
3009class BitwiseOr(Binary):
3010    pass
class BitwiseRightShift(Binary):
3013class BitwiseRightShift(Binary):
3014    pass
class BitwiseXor(Binary):
3017class BitwiseXor(Binary):
3018    pass
class Div(Binary):
3021class Div(Binary):
3022    pass
class Overlaps(Binary):
3025class Overlaps(Binary):
3026    pass
class Dot(Binary):
3029class Dot(Binary):
3030    @property
3031    def name(self) -> str:
3032        return self.expression.name
3033
3034    @classmethod
3035    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3036        """Build a Dot object with a sequence of expressions."""
3037        if len(expressions) < 2:
3038            raise ValueError(f"Dot requires >= 2 expressions.")
3039
3040        a, b, *expressions = expressions
3041        dot = Dot(this=a, expression=b)
3042
3043        for expression in expressions:
3044            dot = Dot(this=dot, expression=expression)
3045
3046        return dot
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3034    @classmethod
3035    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3036        """Build a Dot object with a sequence of expressions."""
3037        if len(expressions) < 2:
3038            raise ValueError(f"Dot requires >= 2 expressions.")
3039
3040        a, b, *expressions = expressions
3041        dot = Dot(this=a, expression=b)
3042
3043        for expression in expressions:
3044            dot = Dot(this=dot, expression=expression)
3045
3046        return dot

Build a Dot object with a sequence of expressions.

class DPipe(Binary):
3049class DPipe(Binary):
3050    pass
class EQ(Binary, Predicate):
3053class EQ(Binary, Predicate):
3054    pass
class NullSafeEQ(Binary, Predicate):
3057class NullSafeEQ(Binary, Predicate):
3058    pass
class NullSafeNEQ(Binary, Predicate):
3061class NullSafeNEQ(Binary, Predicate):
3062    pass
class Distance(Binary):
3065class Distance(Binary):
3066    pass
class Escape(Binary):
3069class Escape(Binary):
3070    pass
class Glob(Binary, Predicate):
3073class Glob(Binary, Predicate):
3074    pass
class GT(Binary, Predicate):
3077class GT(Binary, Predicate):
3078    pass
class GTE(Binary, Predicate):
3081class GTE(Binary, Predicate):
3082    pass
class ILike(Binary, Predicate):
3085class ILike(Binary, Predicate):
3086    pass
class ILikeAny(Binary, Predicate):
3089class ILikeAny(Binary, Predicate):
3090    pass
class IntDiv(Binary):
3093class IntDiv(Binary):
3094    pass
class Is(Binary, Predicate):
3097class Is(Binary, Predicate):
3098    pass
class Kwarg(Binary):
3101class Kwarg(Binary):
3102    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

class Like(Binary, Predicate):
3105class Like(Binary, Predicate):
3106    pass
class LikeAny(Binary, Predicate):
3109class LikeAny(Binary, Predicate):
3110    pass
class LT(Binary, Predicate):
3113class LT(Binary, Predicate):
3114    pass
class LTE(Binary, Predicate):
3117class LTE(Binary, Predicate):
3118    pass
class Mod(Binary):
3121class Mod(Binary):
3122    pass
class Mul(Binary):
3125class Mul(Binary):
3126    pass
class NEQ(Binary, Predicate):
3129class NEQ(Binary, Predicate):
3130    pass
class SimilarTo(Binary, Predicate):
3133class SimilarTo(Binary, Predicate):
3134    pass
class Slice(Binary):
3137class Slice(Binary):
3138    arg_types = {"this": False, "expression": False}
class Sub(Binary):
3141class Sub(Binary):
3142    pass
class ArrayOverlaps(Binary):
3145class ArrayOverlaps(Binary):
3146    pass
class Unary(Expression):
3151class Unary(Expression):
3152    pass
class BitwiseNot(Unary):
3155class BitwiseNot(Unary):
3156    pass
class Not(Unary, Condition):
3159class Not(Unary, Condition):
3160    pass
class Paren(Unary, Condition):
3163class Paren(Unary, Condition):
3164    arg_types = {"this": True, "with": False}
class Neg(Unary):
3167class Neg(Unary):
3168    pass
class Alias(Expression):
3172class Alias(Expression):
3173    arg_types = {"this": True, "alias": False}
3174
3175    @property
3176    def output_name(self):
3177        return self.alias
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
class Aliases(Expression):
3180class Aliases(Expression):
3181    arg_types = {"this": True, "expressions": True}
3182
3183    @property
3184    def aliases(self):
3185        return self.expressions
class AtTimeZone(Expression):
3188class AtTimeZone(Expression):
3189    arg_types = {"this": True, "zone": True}
class Between(Predicate):
3192class Between(Predicate):
3193    arg_types = {"this": True, "low": True, "high": True}
class Bracket(Condition):
3196class Bracket(Condition):
3197    arg_types = {"this": True, "expressions": True}
class Distinct(Expression):
3200class Distinct(Expression):
3201    arg_types = {"expressions": False, "on": False}
class In(Predicate):
3204class In(Predicate):
3205    arg_types = {
3206        "this": True,
3207        "expressions": False,
3208        "query": False,
3209        "unnest": False,
3210        "field": False,
3211        "is_global": False,
3212    }
class TimeUnit(Expression):
3215class TimeUnit(Expression):
3216    """Automatically converts unit arg into a var."""
3217
3218    arg_types = {"unit": False}
3219
3220    def __init__(self, **args):
3221        unit = args.get("unit")
3222        if isinstance(unit, (Column, Literal)):
3223            args["unit"] = Var(this=unit.name)
3224        elif isinstance(unit, Week):
3225            unit.set("this", Var(this=unit.this.name))
3226        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3220    def __init__(self, **args):
3221        unit = args.get("unit")
3222        if isinstance(unit, (Column, Literal)):
3223            args["unit"] = Var(this=unit.name)
3224        elif isinstance(unit, Week):
3225            unit.set("this", Var(this=unit.this.name))
3226        super().__init__(**args)
class Interval(TimeUnit):
3229class Interval(TimeUnit):
3230    arg_types = {"this": False, "unit": False}
class IgnoreNulls(Expression):
3233class IgnoreNulls(Expression):
3234    pass
class RespectNulls(Expression):
3237class RespectNulls(Expression):
3238    pass
class Func(Condition):
3242class Func(Condition):
3243    """
3244    The base class for all function expressions.
3245
3246    Attributes:
3247        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3248            treated as a variable length argument and the argument's value will be stored as a list.
3249        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3250            for this function expression. These values are used to map this node to a name during parsing
3251            as well as to provide the function's name during SQL string generation. By default the SQL
3252            name is set to the expression's class name transformed to snake case.
3253    """
3254
3255    is_var_len_args = False
3256
3257    @classmethod
3258    def from_arg_list(cls, args):
3259        if cls.is_var_len_args:
3260            all_arg_keys = list(cls.arg_types)
3261            # If this function supports variable length argument treat the last argument as such.
3262            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3263            num_non_var = len(non_var_len_arg_keys)
3264
3265            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3266            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3267        else:
3268            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3269
3270        return cls(**args_dict)
3271
3272    @classmethod
3273    def sql_names(cls):
3274        if cls is Func:
3275            raise NotImplementedError(
3276                "SQL name is only supported by concrete function implementations"
3277            )
3278        if "_sql_names" not in cls.__dict__:
3279            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3280        return cls._sql_names
3281
3282    @classmethod
3283    def sql_name(cls):
3284        return cls.sql_names()[0]
3285
3286    @classmethod
3287    def default_parser_mappings(cls):
3288        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
@classmethod
def from_arg_list(cls, args):
3257    @classmethod
3258    def from_arg_list(cls, args):
3259        if cls.is_var_len_args:
3260            all_arg_keys = list(cls.arg_types)
3261            # If this function supports variable length argument treat the last argument as such.
3262            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3263            num_non_var = len(non_var_len_arg_keys)
3264
3265            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3266            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3267        else:
3268            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3269
3270        return cls(**args_dict)
@classmethod
def sql_names(cls):
3272    @classmethod
3273    def sql_names(cls):
3274        if cls is Func:
3275            raise NotImplementedError(
3276                "SQL name is only supported by concrete function implementations"
3277            )
3278        if "_sql_names" not in cls.__dict__:
3279            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3280        return cls._sql_names
@classmethod
def sql_name(cls):
3282    @classmethod
3283    def sql_name(cls):
3284        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3286    @classmethod
3287    def default_parser_mappings(cls):
3288        return {name: cls.from_arg_list for name in cls.sql_names()}
class AggFunc(Func):
3291class AggFunc(Func):
3292    pass
class Abs(Func):
3295class Abs(Func):
3296    pass
class Anonymous(Func):
3299class Anonymous(Func):
3300    arg_types = {"this": True, "expressions": False}
3301    is_var_len_args = True
class Hll(AggFunc):
3306class Hll(AggFunc):
3307    arg_types = {"this": True, "expressions": False}
3308    is_var_len_args = True
class ApproxDistinct(AggFunc):
3311class ApproxDistinct(AggFunc):
3312    arg_types = {"this": True, "accuracy": False}
class Array(Func):
3315class Array(Func):
3316    arg_types = {"expressions": False}
3317    is_var_len_args = True
class ToChar(Func):
3321class ToChar(Func):
3322    arg_types = {"this": True, "format": False}
class GenerateSeries(Func):
3325class GenerateSeries(Func):
3326    arg_types = {"start": True, "end": True, "step": False}
class ArrayAgg(AggFunc):
3329class ArrayAgg(AggFunc):
3330    pass
class ArrayAll(Func):
3333class ArrayAll(Func):
3334    arg_types = {"this": True, "expression": True}
class ArrayAny(Func):
3337class ArrayAny(Func):
3338    arg_types = {"this": True, "expression": True}
class ArrayConcat(Func):
3341class ArrayConcat(Func):
3342    arg_types = {"this": True, "expressions": False}
3343    is_var_len_args = True
class ArrayContains(Binary, Func):
3346class ArrayContains(Binary, Func):
3347    pass
class ArrayContained(Binary):
3350class ArrayContained(Binary):
3351    pass
class ArrayFilter(Func):
3354class ArrayFilter(Func):
3355    arg_types = {"this": True, "expression": True}
3356    _sql_names = ["FILTER", "ARRAY_FILTER"]
class ArrayJoin(Func):
3359class ArrayJoin(Func):
3360    arg_types = {"this": True, "expression": True, "null": False}
class ArraySize(Func):
3363class ArraySize(Func):
3364    arg_types = {"this": True, "expression": False}
class ArraySort(Func):
3367class ArraySort(Func):
3368    arg_types = {"this": True, "expression": False}
class ArraySum(Func):
3371class ArraySum(Func):
3372    pass
class ArrayUnionAgg(AggFunc):
3375class ArrayUnionAgg(AggFunc):
3376    pass
class Avg(AggFunc):
3379class Avg(AggFunc):
3380    pass
class AnyValue(AggFunc):
3383class AnyValue(AggFunc):
3384    pass
class Case(Func):
3387class Case(Func):
3388    arg_types = {"this": False, "ifs": True, "default": False}
class Cast(Func):
3391class Cast(Func):
3392    arg_types = {"this": True, "to": True}
3393
3394    @property
3395    def name(self) -> str:
3396        return self.this.name
3397
3398    @property
3399    def to(self):
3400        return self.args["to"]
3401
3402    @property
3403    def output_name(self):
3404        return self.name
3405
3406    def is_type(self, dtype: DataType.Type) -> bool:
3407        return self.to.is_type(dtype)
output_name

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type(self, dtype: sqlglot.expressions.DataType.Type) -> bool:
3406    def is_type(self, dtype: DataType.Type) -> bool:
3407        return self.to.is_type(dtype)
class Collate(Binary):
3410class Collate(Binary):
3411    pass
class TryCast(Cast):
3414class TryCast(Cast):
3415    pass
class Ceil(Func):
3418class Ceil(Func):
3419    arg_types = {"this": True, "decimals": False}
3420    _sql_names = ["CEIL", "CEILING"]
class Coalesce(Func):
3423class Coalesce(Func):
3424    arg_types = {"this": True, "expressions": False}
3425    is_var_len_args = True
class Concat(Func):
3428class Concat(Func):
3429    arg_types = {"expressions": True}
3430    is_var_len_args = True
class ConcatWs(Concat):
3433class ConcatWs(Concat):
3434    _sql_names = ["CONCAT_WS"]
class Count(AggFunc):
3437class Count(AggFunc):
3438    arg_types = {"this": False}
class CountIf(AggFunc):
3441class CountIf(AggFunc):
3442    pass
class CurrentDate(Func):
3445class CurrentDate(Func):
3446    arg_types = {"this": False}
class CurrentDatetime(Func):
3449class CurrentDatetime(Func):
3450    arg_types = {"this": False}
class CurrentTime(Func):
3453class CurrentTime(Func):
3454    arg_types = {"this": False}
class CurrentTimestamp(Func):
3457class CurrentTimestamp(Func):
3458    arg_types = {"this": False}
class CurrentUser(Func):
3461class CurrentUser(Func):
3462    arg_types = {"this": False}
class DateAdd(Func, TimeUnit):
3465class DateAdd(Func, TimeUnit):
3466    arg_types = {"this": True, "expression": True, "unit": False}
class DateSub(Func, TimeUnit):
3469class DateSub(Func, TimeUnit):
3470    arg_types = {"this": True, "expression": True, "unit": False}
class DateDiff(Func, TimeUnit):
3473class DateDiff(Func, TimeUnit):
3474    _sql_names = ["DATEDIFF", "DATE_DIFF"]
3475    arg_types = {"this": True, "expression": True, "unit": False}
class DateTrunc(Func):
3478class DateTrunc(Func):
3479    arg_types = {"unit": True, "this": True, "zone": False}
class DatetimeAdd(Func, TimeUnit):
3482class DatetimeAdd(Func, TimeUnit):
3483    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeSub(Func, TimeUnit):
3486class DatetimeSub(Func, TimeUnit):
3487    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeDiff(Func, TimeUnit):
3490class DatetimeDiff(Func, TimeUnit):
3491    arg_types = {"this": True, "expression": True, "unit": False}
class DatetimeTrunc(Func, TimeUnit):
3494class DatetimeTrunc(Func, TimeUnit):
3495    arg_types = {"this": True, "unit": True, "zone": False}
class DayOfWeek(Func):
3498class DayOfWeek(Func):
3499    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
class DayOfMonth(Func):
3502class DayOfMonth(Func):
3503    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
class DayOfYear(Func):
3506class DayOfYear(Func):
3507    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
class WeekOfYear(Func):
3510class WeekOfYear(Func):
3511    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
class LastDateOfMonth(Func):
3514class LastDateOfMonth(Func):
3515    pass
class Extract(Func):
3518class Extract(Func):
3519    arg_types = {"this": True, "expression": True}
class TimestampAdd(Func, TimeUnit):
3522class TimestampAdd(Func, TimeUnit):
3523    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampSub(Func, TimeUnit):
3526class TimestampSub(Func, TimeUnit):
3527    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampDiff(Func, TimeUnit):
3530class TimestampDiff(Func, TimeUnit):
3531    arg_types = {"this": True, "expression": True, "unit": False}
class TimestampTrunc(Func, TimeUnit):
3534class TimestampTrunc(Func, TimeUnit):
3535    arg_types = {"this": True, "unit": True, "zone": False}
class TimeAdd(Func, TimeUnit):
3538class TimeAdd(Func, TimeUnit):
3539    arg_types = {"this": True, "expression": True, "unit": False}
class TimeSub(Func, TimeUnit):
3542class TimeSub(Func, TimeUnit):
3543    arg_types = {"this": True, "expression": True, "unit": False}
class TimeDiff(Func, TimeUnit):
3546class TimeDiff(Func, TimeUnit):
3547    arg_types = {"this": True, "expression": True, "unit": False}
class TimeTrunc(Func, TimeUnit):
3550class TimeTrunc(Func, TimeUnit):
3551    arg_types = {"this": True, "unit": True, "zone": False}
class DateFromParts(Func):
3554class DateFromParts(Func):
3555    _sql_names = ["DATEFROMPARTS"]
3556    arg_types = {"year": True, "month": True, "day": True}
class DateStrToDate(Func):
3559class DateStrToDate(Func):
3560    pass
class DateToDateStr(Func):
3563class DateToDateStr(Func):
3564    pass
class DateToDi(Func):
3567class DateToDi(Func):
3568    pass
class Day(Func):
3571class Day(Func):
3572    pass
class Decode(Func):
3575class Decode(Func):
3576    arg_types = {"this": True, "charset": True, "replace": False}
class DiToDate(Func):
3579class DiToDate(Func):
3580    pass
class Encode(Func):
3583class Encode(Func):
3584    arg_types = {"this": True, "charset": True}
class Exp(Func):
3587class Exp(Func):
3588    pass
class Explode(Func):
3591class Explode(Func):
3592    pass
class ExponentialTimeDecayedAvg(AggFunc):
3595class ExponentialTimeDecayedAvg(AggFunc):
3596    arg_types = {"this": True, "time": False, "decay": False}
class Floor(Func):
3599class Floor(Func):
3600    arg_types = {"this": True, "decimals": False}
class Greatest(Func):
3603class Greatest(Func):
3604    arg_types = {"this": True, "expressions": False}
3605    is_var_len_args = True
class GroupConcat(Func):
3608class GroupConcat(Func):
3609    arg_types = {"this": True, "separator": False}
class GroupUniqArray(AggFunc):
3612class GroupUniqArray(AggFunc):
3613    arg_types = {"this": True, "size": False}
class Hex(Func):
3616class Hex(Func):
3617    pass
class Histogram(AggFunc):
3620class Histogram(AggFunc):
3621    arg_types = {"this": True, "bins": False}
class If(Func):
3624class If(Func):
3625    arg_types = {"this": True, "true": True, "false": False}
class IfNull(Func):
3628class IfNull(Func):
3629    arg_types = {"this": True, "expression": False}
3630    _sql_names = ["IFNULL", "NVL"]
class Initcap(Func):
3633class Initcap(Func):
3634    pass
class JSONKeyValue(Expression):
3637class JSONKeyValue(Expression):
3638    arg_types = {"this": True, "expression": True}
class JSONObject(Func):
3641class JSONObject(Func):
3642    arg_types = {
3643        "expressions": False,
3644        "null_handling": False,
3645        "unique_keys": False,
3646        "return_type": False,
3647        "format_json": False,
3648        "encoding": False,
3649    }
class JSONBContains(Binary):
3652class JSONBContains(Binary):
3653    _sql_names = ["JSONB_CONTAINS"]
class JSONExtract(Binary, Func):
3656class JSONExtract(Binary, Func):
3657    _sql_names = ["JSON_EXTRACT"]
class JSONExtractScalar(JSONExtract):
3660class JSONExtractScalar(JSONExtract):
3661    _sql_names = ["JSON_EXTRACT_SCALAR"]
class JSONBExtract(JSONExtract):
3664class JSONBExtract(JSONExtract):
3665    _sql_names = ["JSONB_EXTRACT"]
class JSONBExtractScalar(JSONExtract):
3668class JSONBExtractScalar(JSONExtract):
3669    _sql_names = ["JSONB_EXTRACT_SCALAR"]
class JSONFormat(Func):
3672class JSONFormat(Func):
3673    arg_types = {"this": False, "options": False}
3674    _sql_names = ["JSON_FORMAT"]
class Least(Func):
3677class Least(Func):
3678    arg_types = {"expressions": False}
3679    is_var_len_args = True
class Length(Func):
3682class Length(Func):
3683    pass
class Levenshtein(Func):
3686class Levenshtein(Func):
3687    arg_types = {
3688        "this": True,
3689        "expression": False,
3690        "ins_cost": False,
3691        "del_cost": False,
3692        "sub_cost": False,
3693    }
class Ln(Func):
3696class Ln(Func):
3697    pass
class Log(Func):
3700class Log(Func):
3701    arg_types = {"this": True, "expression": False}
class Log2(Func):
3704class Log2(Func):
3705    pass
class Log10(Func):
3708class Log10(Func):
3709    pass
class LogicalOr(AggFunc):
3712class LogicalOr(AggFunc):
3713    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
class LogicalAnd(AggFunc):
3716class LogicalAnd(AggFunc):
3717    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
class Lower(Func):
3720class Lower(Func):
3721    _sql_names = ["LOWER", "LCASE"]
class Map(Func):
3724class Map(Func):
3725    arg_types = {"keys": False, "values": False}
class VarMap(Func):
3728class VarMap(Func):
3729    arg_types = {"keys": True, "values": True}
3730    is_var_len_args = True
class MatchAgainst(Func):
3734class MatchAgainst(Func):
3735    arg_types = {"this": True, "expressions": True, "modifier": False}
class Max(AggFunc):
3738class Max(AggFunc):
3739    arg_types = {"this": True, "expressions": False}
3740    is_var_len_args = True
class Min(AggFunc):
3743class Min(AggFunc):
3744    arg_types = {"this": True, "expressions": False}
3745    is_var_len_args = True
class Month(Func):
3748class Month(Func):
3749    pass
class Nvl2(Func):
3752class Nvl2(Func):
3753    arg_types = {"this": True, "true": True, "false": False}
class Posexplode(Func):
3756class Posexplode(Func):
3757    pass
class Pow(Binary, Func):
3760class Pow(Binary, Func):
3761    _sql_names = ["POWER", "POW"]
class PercentileCont(AggFunc):
3764class PercentileCont(AggFunc):
3765    pass
class PercentileDisc(AggFunc):
3768class PercentileDisc(AggFunc):
3769    pass
class Quantile(AggFunc):
3772class Quantile(AggFunc):
3773    arg_types = {"this": True, "quantile": True}
class Quantiles(AggFunc):
3778class Quantiles(AggFunc):
3779    arg_types = {"parameters": True, "expressions": True}
3780    is_var_len_args = True
class QuantileIf(AggFunc):
3783class QuantileIf(AggFunc):
3784    arg_types = {"parameters": True, "expressions": True}
class ApproxQuantile(Quantile):
3787class ApproxQuantile(Quantile):
3788    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
class RangeN(Func):
3791class RangeN(Func):
3792    arg_types = {"this": True, "expressions": True, "each": False}
class ReadCSV(Func):
3795class ReadCSV(Func):
3796    _sql_names = ["READ_CSV"]
3797    is_var_len_args = True
3798    arg_types = {"this": True, "expressions": False}
class Reduce(Func):
3801class Reduce(Func):
3802    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
class RegexpExtract(Func):
3805class RegexpExtract(Func):
3806    arg_types = {
3807        "this": True,
3808        "expression": True,
3809        "position": False,
3810        "occurrence": False,
3811        "group": False,
3812    }
class RegexpLike(Func):
3815class RegexpLike(Func):
3816    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpILike(Func):
3819class RegexpILike(Func):
3820    arg_types = {"this": True, "expression": True, "flag": False}
class RegexpSplit(Func):
3825class RegexpSplit(Func):
3826    arg_types = {"this": True, "expression": True, "limit": False}
class Repeat(Func):
3829class Repeat(Func):
3830    arg_types = {"this": True, "times": True}
class Round(Func):
3833class Round(Func):
3834    arg_types = {"this": True, "decimals": False}
class RowNumber(Func):
3837class RowNumber(Func):
3838    arg_types: t.Dict[str, t.Any] = {}
class SafeDivide(Func):
3841class SafeDivide(Func):
3842    arg_types = {"this": True, "expression": True}
class SetAgg(AggFunc):
3845class SetAgg(AggFunc):
3846    pass
class SortArray(Func):
3849class SortArray(Func):
3850    arg_types = {"this": True, "asc": False}
class Split(Func):
3853class Split(Func):
3854    arg_types = {"this": True, "expression": True, "limit": False}
class Substring(Func):
3859class Substring(Func):
3860    arg_types = {"this": True, "start": False, "length": False}
class StrPosition(Func):
3863class StrPosition(Func):
3864    arg_types = {
3865        "this": True,
3866        "substr": True,
3867        "position": False,
3868        "instance": False,
3869    }
class StrToDate(Func):
3872class StrToDate(Func):
3873    arg_types = {"this": True, "format": True}
class StrToTime(Func):
3876class StrToTime(Func):
3877    arg_types = {"this": True, "format": True}
class StrToUnix(Func):
3882class StrToUnix(Func):
3883    arg_types = {"this": False, "format": False}
class NumberToStr(Func):
3886class NumberToStr(Func):
3887    arg_types = {"this": True, "format": True}
class Struct(Func):
3890class Struct(Func):
3891    arg_types = {"expressions": True}
3892    is_var_len_args = True
class StructExtract(Func):
3895class StructExtract(Func):
3896    arg_types = {"this": True, "expression": True}
class Sum(AggFunc):
3899class Sum(AggFunc):
3900    pass
class Sqrt(Func):
3903class Sqrt(Func):
3904    pass
class Stddev(AggFunc):
3907class Stddev(AggFunc):
3908    pass
class StddevPop(AggFunc):
3911class StddevPop(AggFunc):
3912    pass
class StddevSamp(AggFunc):
3915class StddevSamp(AggFunc):
3916    pass
class TimeToStr(Func):
3919class TimeToStr(Func):
3920    arg_types = {"this": True, "format": True}
class TimeToTimeStr(Func):
3923class TimeToTimeStr(Func):
3924    pass
class TimeToUnix(Func):
3927class TimeToUnix(Func):
3928    pass
class TimeStrToDate(Func):
3931class TimeStrToDate(Func):
3932    pass
class TimeStrToTime(Func):
3935class TimeStrToTime(Func):
3936    pass
class TimeStrToUnix(Func):
3939class TimeStrToUnix(Func):
3940    pass
class Trim(Func):
3943class Trim(Func):
3944    arg_types = {
3945        "this": True,
3946        "expression": False,
3947        "position": False,
3948        "collation": False,
3949    }
class TsOrDsAdd(Func, TimeUnit):
3952class TsOrDsAdd(Func, TimeUnit):
3953    arg_types = {"this": True, "expression": True, "unit": False}
class TsOrDsToDateStr(Func):
3956class TsOrDsToDateStr(Func):
3957    pass
class TsOrDsToDate(Func):
3960class TsOrDsToDate(Func):
3961    arg_types = {"this": True, "format": False}
class TsOrDiToDi(Func):
3964class TsOrDiToDi(Func):
3965    pass
class Unhex(Func):
3968class Unhex(Func):
3969    pass
class UnixToStr(Func):
3972class UnixToStr(Func):
3973    arg_types = {"this": True, "format": False}
class UnixToTime(Func):
3978class UnixToTime(Func):
3979    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
3980
3981    SECONDS = Literal.string("seconds")
3982    MILLIS = Literal.string("millis")
3983    MICROS = Literal.string("micros")
class UnixToTimeStr(Func):
3986class UnixToTimeStr(Func):
3987    pass
class Upper(Func):
3990class Upper(Func):
3991    _sql_names = ["UPPER", "UCASE"]
class Variance(AggFunc):
3994class Variance(AggFunc):
3995    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
class VariancePop(AggFunc):
3998class VariancePop(AggFunc):
3999    _sql_names = ["VARIANCE_POP", "VAR_POP"]
class Week(Func):
4002class Week(Func):
4003    arg_types = {"this": True, "mode": False}
class XMLTable(Func):
4006class XMLTable(Func):
4007    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
class Year(Func):
4010class Year(Func):
4011    pass
class Use(Expression):
4014class Use(Expression):
4015    arg_types = {"this": True, "kind": False}
class Merge(Expression):
4018class Merge(Expression):
4019    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
class When(Func):
4022class When(Func):
4023    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4034def maybe_parse(
4035    sql_or_expression: ExpOrStr,
4036    *,
4037    into: t.Optional[IntoType] = None,
4038    dialect: DialectType = None,
4039    prefix: t.Optional[str] = None,
4040    copy: bool = False,
4041    **opts,
4042) -> Expression:
4043    """Gracefully handle a possible string or expression.
4044
4045    Example:
4046        >>> maybe_parse("1")
4047        (LITERAL this: 1, is_string: False)
4048        >>> maybe_parse(to_identifier("x"))
4049        (IDENTIFIER this: x, quoted: False)
4050
4051    Args:
4052        sql_or_expression: the SQL code string or an expression
4053        into: the SQLGlot Expression to parse into
4054        dialect: the dialect used to parse the input expressions (in the case that an
4055            input expression is a SQL string).
4056        prefix: a string to prefix the sql with before it gets parsed
4057            (automatically includes a space)
4058        copy: whether or not to copy the expression.
4059        **opts: other options to use to parse the input expressions (again, in the case
4060            that an input expression is a SQL string).
4061
4062    Returns:
4063        Expression: the parsed or given expression.
4064    """
4065    if isinstance(sql_or_expression, Expression):
4066        if copy:
4067            return sql_or_expression.copy()
4068        return sql_or_expression
4069
4070    import sqlglot
4071
4072    sql = str(sql_or_expression)
4073    if prefix:
4074        sql = f"{prefix} {sql}"
4075    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union(left, right, distinct=True, dialect=None, **opts):
4221def union(left, right, distinct=True, dialect=None, **opts):
4222    """
4223    Initializes a syntax tree from one UNION expression.
4224
4225    Example:
4226        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4227        'SELECT * FROM foo UNION SELECT * FROM bla'
4228
4229    Args:
4230        left (str | Expression): the SQL code string corresponding to the left-hand side.
4231            If an `Expression` instance is passed, it will be used as-is.
4232        right (str | Expression): the SQL code string corresponding to the right-hand side.
4233            If an `Expression` instance is passed, it will be used as-is.
4234        distinct (bool): set the DISTINCT flag if and only if this is true.
4235        dialect (str): the dialect used to parse the input expression.
4236        opts (kwargs): other options to use to parse the input expressions.
4237    Returns:
4238        Union: the syntax tree for the UNION expression.
4239    """
4240    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4241    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4242
4243    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Union: the syntax tree for the UNION expression.

def intersect(left, right, distinct=True, dialect=None, **opts):
4246def intersect(left, right, distinct=True, dialect=None, **opts):
4247    """
4248    Initializes a syntax tree from one INTERSECT expression.
4249
4250    Example:
4251        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4252        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4253
4254    Args:
4255        left (str | Expression): the SQL code string corresponding to the left-hand side.
4256            If an `Expression` instance is passed, it will be used as-is.
4257        right (str | Expression): the SQL code string corresponding to the right-hand side.
4258            If an `Expression` instance is passed, it will be used as-is.
4259        distinct (bool): set the DISTINCT flag if and only if this is true.
4260        dialect (str): the dialect used to parse the input expression.
4261        opts (kwargs): other options to use to parse the input expressions.
4262    Returns:
4263        Intersect: the syntax tree for the INTERSECT expression.
4264    """
4265    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4266    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4267
4268    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Intersect: the syntax tree for the INTERSECT expression.

def except_(left, right, distinct=True, dialect=None, **opts):
4271def except_(left, right, distinct=True, dialect=None, **opts):
4272    """
4273    Initializes a syntax tree from one EXCEPT expression.
4274
4275    Example:
4276        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4277        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4278
4279    Args:
4280        left (str | Expression): the SQL code string corresponding to the left-hand side.
4281            If an `Expression` instance is passed, it will be used as-is.
4282        right (str | Expression): the SQL code string corresponding to the right-hand side.
4283            If an `Expression` instance is passed, it will be used as-is.
4284        distinct (bool): set the DISTINCT flag if and only if this is true.
4285        dialect (str): the dialect used to parse the input expression.
4286        opts (kwargs): other options to use to parse the input expressions.
4287    Returns:
4288        Except: the syntax tree for the EXCEPT statement.
4289    """
4290    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4291    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4292
4293    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left (str | Expression): the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right (str | Expression): the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct (bool): set the DISTINCT flag if and only if this is true.
  • dialect (str): the dialect used to parse the input expression.
  • opts (kwargs): other options to use to parse the input expressions.
Returns:

Except: the syntax tree for the EXCEPT statement.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4296def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4297    """
4298    Initializes a syntax tree from one or multiple SELECT expressions.
4299
4300    Example:
4301        >>> select("col1", "col2").from_("tbl").sql()
4302        'SELECT col1, col2 FROM tbl'
4303
4304    Args:
4305        *expressions: the SQL code string to parse as the expressions of a
4306            SELECT statement. If an Expression instance is passed, this is used as-is.
4307        dialect: the dialect used to parse the input expressions (in the case that an
4308            input expression is a SQL string).
4309        **opts: other options to use to parse the input expressions (again, in the case
4310            that an input expression is a SQL string).
4311
4312    Returns:
4313        Select: the syntax tree for the SELECT statement.
4314    """
4315    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Select:
4318def from_(*expressions, dialect=None, **opts) -> Select:
4319    """
4320    Initializes a syntax tree from a FROM expression.
4321
4322    Example:
4323        >>> from_("tbl").select("col1", "col2").sql()
4324        'SELECT col1, col2 FROM tbl'
4325
4326    Args:
4327        *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a
4328            SELECT statement. If an Expression instance is passed, this is used as-is.
4329        dialect (str): the dialect used to parse the input expression (in the case that the
4330            input expression is a SQL string).
4331        **opts: other options to use to parse the input expressions (again, in the case
4332            that the input expression is a SQL string).
4333
4334    Returns:
4335        Select: the syntax tree for the SELECT statement.
4336    """
4337    return Select().from_(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions (str | Expression): the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
4340def update(
4341    table: str | Table,
4342    properties: dict,
4343    where: t.Optional[ExpOrStr] = None,
4344    from_: t.Optional[ExpOrStr] = None,
4345    dialect: DialectType = None,
4346    **opts,
4347) -> Update:
4348    """
4349    Creates an update statement.
4350
4351    Example:
4352        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
4353        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
4354
4355    Args:
4356        *properties: dictionary of properties to set which are
4357            auto converted to sql objects eg None -> NULL
4358        where: sql conditional parsed into a WHERE statement
4359        from_: sql statement parsed into a FROM statement
4360        dialect: the dialect used to parse the input expressions.
4361        **opts: other options to use to parse the input expressions.
4362
4363    Returns:
4364        Update: the syntax tree for the UPDATE statement.
4365    """
4366    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
4367    update_expr.set(
4368        "expressions",
4369        [
4370            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
4371            for k, v in properties.items()
4372        ],
4373    )
4374    if from_:
4375        update_expr.set(
4376            "from",
4377            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
4378        )
4379    if isinstance(where, Condition):
4380        where = Where(this=where)
4381    if where:
4382        update_expr.set(
4383            "where",
4384            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
4385        )
4386    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
4389def delete(
4390    table: ExpOrStr,
4391    where: t.Optional[ExpOrStr] = None,
4392    returning: t.Optional[ExpOrStr] = None,
4393    dialect: DialectType = None,
4394    **opts,
4395) -> Delete:
4396    """
4397    Builds a delete statement.
4398
4399    Example:
4400        >>> delete("my_table", where="id > 1").sql()
4401        'DELETE FROM my_table WHERE id > 1'
4402
4403    Args:
4404        where: sql conditional parsed into a WHERE statement
4405        returning: sql conditional parsed into a RETURNING statement
4406        dialect: the dialect used to parse the input expressions.
4407        **opts: other options to use to parse the input expressions.
4408
4409    Returns:
4410        Delete: the syntax tree for the DELETE statement.
4411    """
4412    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
4413    if where:
4414        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
4415    if returning:
4416        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
4417    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def condition(expression, dialect=None, **opts) -> sqlglot.expressions.Condition:
4420def condition(expression, dialect=None, **opts) -> Condition:
4421    """
4422    Initialize a logical condition expression.
4423
4424    Example:
4425        >>> condition("x=1").sql()
4426        'x = 1'
4427
4428        This is helpful for composing larger logical syntax trees:
4429        >>> where = condition("x=1")
4430        >>> where = where.and_("y=1")
4431        >>> Select().from_("tbl").select("*").where(where).sql()
4432        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
4433
4434    Args:
4435        *expression (str | Expression): the SQL code string to parse.
4436            If an Expression instance is passed, this is used as-is.
4437        dialect (str): the dialect used to parse the input expression (in the case that the
4438            input expression is a SQL string).
4439        **opts: other options to use to parse the input expressions (again, in the case
4440            that the input expression is a SQL string).
4441
4442    Returns:
4443        Condition: the expression
4444    """
4445    return maybe_parse(  # type: ignore
4446        expression,
4447        into=Condition,
4448        dialect=dialect,
4449        **opts,
4450    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression (str | Expression): the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Condition: the expression

def and_(*expressions, dialect=None, **opts) -> sqlglot.expressions.And:
4453def and_(*expressions, dialect=None, **opts) -> And:
4454    """
4455    Combine multiple conditions with an AND logical operator.
4456
4457    Example:
4458        >>> and_("x=1", and_("y=1", "z=1")).sql()
4459        'x = 1 AND (y = 1 AND z = 1)'
4460
4461    Args:
4462        *expressions (str | Expression): the SQL code strings to parse.
4463            If an Expression instance is passed, this is used as-is.
4464        dialect (str): the dialect used to parse the input expression.
4465        **opts: other options to use to parse the input expressions.
4466
4467    Returns:
4468        And: the new condition
4469    """
4470    return _combine(expressions, And, dialect, **opts)

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_(*expressions, dialect=None, **opts) -> sqlglot.expressions.Or:
4473def or_(*expressions, dialect=None, **opts) -> Or:
4474    """
4475    Combine multiple conditions with an OR logical operator.
4476
4477    Example:
4478        >>> or_("x=1", or_("y=1", "z=1")).sql()
4479        'x = 1 OR (y = 1 OR z = 1)'
4480
4481    Args:
4482        *expressions (str | Expression): the SQL code strings to parse.
4483            If an Expression instance is passed, this is used as-is.
4484        dialect (str): the dialect used to parse the input expression.
4485        **opts: other options to use to parse the input expressions.
4486
4487    Returns:
4488        Or: the new condition
4489    """
4490    return _combine(expressions, Or, dialect, **opts)

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_(expression, dialect=None, **opts) -> sqlglot.expressions.Not:
4493def not_(expression, dialect=None, **opts) -> Not:
4494    """
4495    Wrap a condition with a NOT operator.
4496
4497    Example:
4498        >>> not_("this_suit='black'").sql()
4499        "NOT this_suit = 'black'"
4500
4501    Args:
4502        expression (str | Expression): the SQL code strings to parse.
4503            If an Expression instance is passed, this is used as-is.
4504        dialect (str): the dialect used to parse the input expression.
4505        **opts: other options to use to parse the input expressions.
4506
4507    Returns:
4508        Not: the new condition
4509    """
4510    this = condition(
4511        expression,
4512        dialect=dialect,
4513        **opts,
4514    )
4515    return Not(this=_wrap_operator(this))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Not: the new condition

def paren(expression) -> sqlglot.expressions.Paren:
4518def paren(expression) -> Paren:
4519    return Paren(this=expression)
def to_identifier(name, quoted=None):
4535def to_identifier(name, quoted=None):
4536    """Builds an identifier.
4537
4538    Args:
4539        name: The name to turn into an identifier.
4540        quoted: Whether or not force quote the identifier.
4541
4542    Returns:
4543        The identifier ast node.
4544    """
4545
4546    if name is None:
4547        return None
4548
4549    if isinstance(name, Identifier):
4550        identifier = name
4551    elif isinstance(name, str):
4552        identifier = Identifier(
4553            this=name,
4554            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
4555        )
4556    else:
4557        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
4558    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
Returns:

The identifier ast node.

def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
4564def to_interval(interval: str | Literal) -> Interval:
4565    """Builds an interval expression from a string like '1 day' or '5 months'."""
4566    if isinstance(interval, Literal):
4567        if not interval.is_string:
4568            raise ValueError("Invalid interval string.")
4569
4570        interval = interval.this
4571
4572    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
4573
4574    if not interval_parts:
4575        raise ValueError("Invalid interval string.")
4576
4577    return Interval(
4578        this=Literal.string(interval_parts.group(1)),
4579        unit=Var(this=interval_parts.group(2)),
4580    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], **kwargs) -> Optional[sqlglot.expressions.Table]:
4593def to_table(sql_path: t.Optional[str | Table], **kwargs) -> t.Optional[Table]:
4594    """
4595    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
4596    If a table is passed in then that table is returned.
4597
4598    Args:
4599        sql_path: a `[catalog].[schema].[table]` string.
4600
4601    Returns:
4602        A table expression.
4603    """
4604    if sql_path is None or isinstance(sql_path, Table):
4605        return sql_path
4606    if not isinstance(sql_path, str):
4607        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
4608
4609    catalog, db, table_name = (to_identifier(x) for x in split_num_words(sql_path, ".", 3))
4610    return Table(this=table_name, db=db, catalog=catalog, **kwargs)

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
4613def to_column(sql_path: str | Column, **kwargs) -> Column:
4614    """
4615    Create a column from a `[table].[column]` sql path. Schema is optional.
4616
4617    If a column is passed in then that column is returned.
4618
4619    Args:
4620        sql_path: `[table].[column]` string
4621    Returns:
4622        Table: A column expression
4623    """
4624    if sql_path is None or isinstance(sql_path, Column):
4625        return sql_path
4626    if not isinstance(sql_path, str):
4627        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
4628    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts):
4631def alias_(
4632    expression: ExpOrStr,
4633    alias: str | Identifier,
4634    table: bool | t.Sequence[str | Identifier] = False,
4635    quoted: t.Optional[bool] = None,
4636    dialect: DialectType = None,
4637    **opts,
4638):
4639    """Create an Alias expression.
4640
4641    Example:
4642        >>> alias_('foo', 'bar').sql()
4643        'foo AS bar'
4644
4645        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
4646        '(SELECT 1, 2) AS bar(a, b)'
4647
4648    Args:
4649        expression: the SQL code strings to parse.
4650            If an Expression instance is passed, this is used as-is.
4651        alias: the alias name to use. If the name has
4652            special characters it is quoted.
4653        table: Whether or not to create a table alias, can also be a list of columns.
4654        quoted: whether or not to quote the alias
4655        dialect: the dialect used to parse the input expression.
4656        **opts: other options to use to parse the input expressions.
4657
4658    Returns:
4659        Alias: the aliased expression
4660    """
4661    exp = maybe_parse(expression, dialect=dialect, **opts)
4662    alias = to_identifier(alias, quoted=quoted)
4663
4664    if table:
4665        table_alias = TableAlias(this=alias)
4666        exp.set("alias", table_alias)
4667
4668        if not isinstance(table, bool):
4669            for column in table:
4670                table_alias.append("columns", to_identifier(column, quoted=quoted))
4671
4672        return exp
4673
4674    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
4675    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
4676    # for the complete Window expression.
4677    #
4678    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
4679
4680    if "alias" in exp.arg_types and not isinstance(exp, Window):
4681        exp = exp.copy()
4682        exp.set("alias", alias)
4683        return exp
4684    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery(expression, alias=None, dialect=None, **opts):
4687def subquery(expression, alias=None, dialect=None, **opts):
4688    """
4689    Build a subquery expression.
4690
4691    Example:
4692        >>> subquery('select x from tbl', 'bar').select('x').sql()
4693        'SELECT x FROM (SELECT x FROM tbl) AS bar'
4694
4695    Args:
4696        expression (str | Expression): the SQL code strings to parse.
4697            If an Expression instance is passed, this is used as-is.
4698        alias (str | Expression): the alias name to use.
4699        dialect (str): the dialect used to parse the input expression.
4700        **opts: other options to use to parse the input expressions.
4701
4702    Returns:
4703        Select: a new select with the subquery expression included
4704    """
4705
4706    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
4707    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression (str | Expression): the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias (str | Expression): the alias name to use.
  • dialect (str): the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Select: a new select with the subquery expression included

def column( col: str | sqlglot.expressions.Identifier, table: Union[str, sqlglot.expressions.Identifier, NoneType] = None, db: Union[str, sqlglot.expressions.Identifier, NoneType] = None, catalog: Union[str, sqlglot.expressions.Identifier, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
4710def column(
4711    col: str | Identifier,
4712    table: t.Optional[str | Identifier] = None,
4713    db: t.Optional[str | Identifier] = None,
4714    catalog: t.Optional[str | Identifier] = None,
4715    quoted: t.Optional[bool] = None,
4716) -> Column:
4717    """
4718    Build a Column.
4719
4720    Args:
4721        col: column name
4722        table: table name
4723        db: db name
4724        catalog: catalog name
4725        quoted: whether or not to force quote each part
4726    Returns:
4727        Column: column instance
4728    """
4729    return Column(
4730        this=to_identifier(col, quoted=quoted),
4731        table=to_identifier(table, quoted=quoted),
4732        db=to_identifier(db, quoted=quoted),
4733        catalog=to_identifier(catalog, quoted=quoted),
4734    )

Build a Column.

Arguments:
  • col: column name
  • table: table name
  • db: db name
  • catalog: catalog name
  • quoted: whether or not to force quote each part
Returns:

Column: column instance

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
4737def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
4738    """Cast an expression to a data type.
4739
4740    Example:
4741        >>> cast('x + 1', 'int').sql()
4742        'CAST(x + 1 AS INT)'
4743
4744    Args:
4745        expression: The expression to cast.
4746        to: The datatype to cast to.
4747
4748    Returns:
4749        A cast node.
4750    """
4751    expression = maybe_parse(expression, **opts)
4752    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

A cast node.

def table_( table, db=None, catalog=None, quoted=None, alias=None) -> sqlglot.expressions.Table:
4755def table_(table, db=None, catalog=None, quoted=None, alias=None) -> Table:
4756    """Build a Table.
4757
4758    Args:
4759        table (str | Expression): column name
4760        db (str | Expression): db name
4761        catalog (str | Expression): catalog name
4762
4763    Returns:
4764        Table: table instance
4765    """
4766    return Table(
4767        this=to_identifier(table, quoted=quoted),
4768        db=to_identifier(db, quoted=quoted),
4769        catalog=to_identifier(catalog, quoted=quoted),
4770        alias=TableAlias(this=to_identifier(alias)) if alias else None,
4771    )

Build a Table.

Arguments:
  • table (str | Expression): column name
  • db (str | Expression): db name
  • catalog (str | Expression): catalog name
Returns:

Table: table instance

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
4774def values(
4775    values: t.Iterable[t.Tuple[t.Any, ...]],
4776    alias: t.Optional[str] = None,
4777    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
4778) -> Values:
4779    """Build VALUES statement.
4780
4781    Example:
4782        >>> values([(1, '2')]).sql()
4783        "VALUES (1, '2')"
4784
4785    Args:
4786        values: values statements that will be converted to SQL
4787        alias: optional alias
4788        columns: Optional list of ordered column names or ordered dictionary of column names to types.
4789         If either are provided then an alias is also required.
4790         If a dictionary is provided then the first column of the values will be casted to the expected type
4791         in order to help with type inference.
4792
4793    Returns:
4794        Values: the Values expression object
4795    """
4796    if columns and not alias:
4797        raise ValueError("Alias is required when providing columns")
4798    table_alias = (
4799        TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
4800        if columns
4801        else TableAlias(this=to_identifier(alias) if alias else None)
4802    )
4803    expressions = [convert(tup) for tup in values]
4804    if columns and isinstance(columns, dict):
4805        types = list(columns.values())
4806        expressions[0].set(
4807            "expressions",
4808            [cast(x, types[i]) for i, x in enumerate(expressions[0].expressions)],
4809        )
4810    return Values(
4811        expressions=expressions,
4812        alias=table_alias,
4813    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required. If a dictionary is provided then the first column of the values will be casted to the expected type in order to help with type inference.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
4816def var(name: t.Optional[ExpOrStr]) -> Var:
4817    """Build a SQL variable.
4818
4819    Example:
4820        >>> repr(var('x'))
4821        '(VAR this: x)'
4822
4823        >>> repr(var(column('x', table='y')))
4824        '(VAR this: x)'
4825
4826    Args:
4827        name: The name of the var or an expression who's name will become the var.
4828
4829    Returns:
4830        The new variable node.
4831    """
4832    if not name:
4833        raise ValueError("Cannot convert empty name into var.")
4834
4835    if isinstance(name, Expression):
4836        name = name.name
4837    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
4840def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
4841    """Build ALTER TABLE... RENAME... expression
4842
4843    Args:
4844        old_name: The old name of the table
4845        new_name: The new name of the table
4846
4847    Returns:
4848        Alter table expression
4849    """
4850    old_table = to_table(old_name)
4851    new_table = to_table(new_name)
4852    return AlterTable(
4853        this=old_table,
4854        actions=[
4855            RenameTable(this=new_table),
4856        ],
4857    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value) -> sqlglot.expressions.Expression:
4860def convert(value) -> Expression:
4861    """Convert a python value into an expression object.
4862
4863    Raises an error if a conversion is not possible.
4864
4865    Args:
4866        value (Any): a python object
4867
4868    Returns:
4869        Expression: the equivalent expression object
4870    """
4871    if isinstance(value, Expression):
4872        return value
4873    if value is None:
4874        return NULL
4875    if isinstance(value, bool):
4876        return Boolean(this=value)
4877    if isinstance(value, str):
4878        return Literal.string(value)
4879    if isinstance(value, float) and math.isnan(value):
4880        return NULL
4881    if isinstance(value, numbers.Number):
4882        return Literal.number(value)
4883    if isinstance(value, tuple):
4884        return Tuple(expressions=[convert(v) for v in value])
4885    if isinstance(value, list):
4886        return Array(expressions=[convert(v) for v in value])
4887    if isinstance(value, dict):
4888        return Map(
4889            keys=[convert(k) for k in value],
4890            values=[convert(v) for v in value.values()],
4891        )
4892    if isinstance(value, datetime.datetime):
4893        datetime_literal = Literal.string(
4894            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
4895        )
4896        return TimeStrToTime(this=datetime_literal)
4897    if isinstance(value, datetime.date):
4898        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
4899        return DateStrToDate(this=date_literal)
4900    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value (Any): a python object
Returns:

Expression: the equivalent expression object

def replace_children(expression, fun, *args, **kwargs):
4903def replace_children(expression, fun, *args, **kwargs):
4904    """
4905    Replace children of an expression with the result of a lambda fun(child) -> exp.
4906    """
4907    for k, v in expression.args.items():
4908        is_list_arg = type(v) is list
4909
4910        child_nodes = v if is_list_arg else [v]
4911        new_child_nodes = []
4912
4913        for cn in child_nodes:
4914            if isinstance(cn, Expression):
4915                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
4916                    new_child_nodes.append(child_node)
4917                    child_node.parent = expression
4918                    child_node.arg_key = k
4919            else:
4920                new_child_nodes.append(cn)
4921
4922        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names(expression):
4925def column_table_names(expression):
4926    """
4927    Return all table names referenced through columns in an expression.
4928
4929    Example:
4930        >>> import sqlglot
4931        >>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
4932        ['c', 'a']
4933
4934    Args:
4935        expression (sqlglot.Expression): expression to find table names
4936
4937    Returns:
4938        list: A list of unique names
4939    """
4940    return list(dict.fromkeys(column.table for column in expression.find_all(Column)))

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e"))
['c', 'a']
Arguments:
  • expression (sqlglot.Expression): expression to find table names
Returns:

list: A list of unique names

def table_name(table) -> str:
4943def table_name(table) -> str:
4944    """Get the full name of a table as a string.
4945
4946    Args:
4947        table (exp.Table | str): table expression node or string.
4948
4949    Examples:
4950        >>> from sqlglot import exp, parse_one
4951        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
4952        'a.b.c'
4953
4954    Returns:
4955        The table name.
4956    """
4957
4958    table = maybe_parse(table, into=Table)
4959
4960    if not table:
4961        raise ValueError(f"Cannot parse {table}")
4962
4963    return ".".join(
4964        part
4965        for part in (
4966            table.text("catalog"),
4967            table.text("db"),
4968            table.name,
4969        )
4970        if part
4971    )

Get the full name of a table as a string.

Arguments:
  • table (exp.Table | str): table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression, mapping):
4974def replace_tables(expression, mapping):
4975    """Replace all tables in expression according to the mapping.
4976
4977    Args:
4978        expression (sqlglot.Expression): expression node to be transformed and replaced.
4979        mapping (Dict[str, str]): mapping of table names.
4980
4981    Examples:
4982        >>> from sqlglot import exp, parse_one
4983        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
4984        'SELECT * FROM c'
4985
4986    Returns:
4987        The mapped expression.
4988    """
4989
4990    def _replace_tables(node):
4991        if isinstance(node, Table):
4992            new_name = mapping.get(table_name(node))
4993            if new_name:
4994                return to_table(
4995                    new_name,
4996                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
4997                )
4998        return node
4999
5000    return expression.transform(_replace_tables)

Replace all tables in expression according to the mapping.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • mapping (Dict[str, str]): mapping of table names.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders(expression, *args, **kwargs):
5003def replace_placeholders(expression, *args, **kwargs):
5004    """Replace placeholders in an expression.
5005
5006    Args:
5007        expression (sqlglot.Expression): expression node to be transformed and replaced.
5008        args: positional names that will substitute unnamed placeholders in the given order.
5009        kwargs: keyword arguments that will substitute named placeholders.
5010
5011    Examples:
5012        >>> from sqlglot import exp, parse_one
5013        >>> replace_placeholders(
5014        ...     parse_one("select * from :tbl where ? = ?"),
5015        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5016        ... ).sql()
5017        "SELECT * FROM foo WHERE str_col = 'b'"
5018
5019    Returns:
5020        The mapped expression.
5021    """
5022
5023    def _replace_placeholders(node, args, **kwargs):
5024        if isinstance(node, Placeholder):
5025            if node.name:
5026                new_name = kwargs.get(node.name)
5027                if new_name:
5028                    return convert(new_name)
5029            else:
5030                try:
5031                    return convert(next(args))
5032                except StopIteration:
5033                    pass
5034        return node
5035
5036    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression (sqlglot.Expression): expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy=True) -> sqlglot.expressions.Expression:
5039def expand(expression: Expression, sources: t.Dict[str, Subqueryable], copy=True) -> Expression:
5040    """Transforms an expression by expanding all referenced sources into subqueries.
5041
5042    Examples:
5043        >>> from sqlglot import parse_one
5044        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5045        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5046
5047    Args:
5048        expression: The expression to expand.
5049        sources: A dictionary of name to Subqueryables.
5050        copy: Whether or not to copy the expression during transformation. Defaults to True.
5051
5052    Returns:
5053        The transformed expression.
5054    """
5055
5056    def _expand(node: Expression):
5057        if isinstance(node, Table):
5058            name = table_name(node)
5059            source = sources.get(name)
5060            if source:
5061                subquery = source.subquery(node.alias or name)
5062                subquery.comments = [f"source: {name}"]
5063                return subquery
5064        return node
5065
5066    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5069def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5070    """
5071    Returns a Func expression.
5072
5073    Examples:
5074        >>> func("abs", 5).sql()
5075        'ABS(5)'
5076
5077        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5078        'CAST(5 AS DOUBLE)'
5079
5080    Args:
5081        name: the name of the function to build.
5082        args: the args used to instantiate the function of interest.
5083        dialect: the source dialect.
5084        kwargs: the kwargs used to instantiate the function of interest.
5085
5086    Note:
5087        The arguments `args` and `kwargs` are mutually exclusive.
5088
5089    Returns:
5090        An instance of the function of interest, or an anonymous function, if `name` doesn't
5091        correspond to an existing `sqlglot.expressions.Func` class.
5092    """
5093    if args and kwargs:
5094        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5095
5096    from sqlglot.dialects.dialect import Dialect
5097
5098    converted = [convert(arg) for arg in args]
5099    kwargs = {key: convert(value) for key, value in kwargs.items()}
5100
5101    parser = Dialect.get_or_raise(dialect)().parser()
5102    from_args_list = parser.FUNCTIONS.get(name.upper())
5103
5104    if from_args_list:
5105        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5106    else:
5107        kwargs = kwargs or {"expressions": converted}
5108        function = Anonymous(this=name, **kwargs)
5109
5110    for error_message in function.error_messages(converted):
5111        raise ValueError(error_message)
5112
5113    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true():
5116def true():
5117    """
5118    Returns a true Boolean expression.
5119    """
5120    return Boolean(this=True)

Returns a true Boolean expression.

def false():
5123def false():
5124    """
5125    Returns a false Boolean expression.
5126    """
5127    return Boolean(this=False)

Returns a false Boolean expression.

def null():
5130def null():
5131    """
5132    Returns a Null expression.
5133    """
5134    return Null()

Returns a Null expression.